使用.NET4.0的dynamic特性解析plist文件及json字符串

1.解析plist文件:

    using System;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;
    using System.Dynamic;
    using System.Collections.Generic; 

    public class DynamicDictionary : DynamicObject
    {
        public IDictionary<string, object> Items;

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (Items == null || !Items.TryGetValue(binder.Name, out result)) result = null;
            if (result is DynamicDictionary) 
                result = (dynamic)result;
            return true;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (Items == null) Items = new Dictionary<string, object>();
            if (value is IDictionary<string, object>)
                value = new DynamicDictionary() { Items = (IDictionary<string, object>)value };
            else if (value is IEnumerable<IDictionary<string, object>>)
                value = from x in (IEnumerable<IDictionary<string, object>>)value select new DynamicDictionary() { Items = x };
            Items[binder.Name] = value;
            return true;
        }
    }

    /// <summary>plist文件解析器</summary>
    public class Plist : DynamicDictionary
    {
        public Plist() 
        {
            Items = new Dictionary<string, object>();
        }

        public Plist(string file)
        {
            var doc = XDocument.Load(file);

            Items = Parse(doc.Element("plist").Element("dict"));
        }

        private static IDictionary<string, object> Parse(XElement dict)
        {
            if (dict == null || dict.Name != "dict")
                throw new ArgumentException();

            var ret = new Dictionary<string, object>();
            var elements = dict.Elements().ToArray();
            for (int i = 0; i < elements.Length; i += 2)
            {
                var key = elements[i].Value;
                var node = elements[i + 1];
                switch (node.Name.LocalName)
                {
                    case "string":
                        ret[key] = node.Value;
                        break;
                    case "real":
                    case "integer":
                        ret[key] = int.Parse(node.Value.Trim());
                        break;
                    case "true":
                        ret[key] = true;
                        break;
                    case "false":
                        ret[key] = false;
                        break;
                    case "date":
                        ret[key] = DateTime.Parse(node.Value.Trim());
                        break;
                    case "data":
                        ret[key] = Convert.FromBase64String(node.Value.Trim());
                        break;
                    case "array":
                        ret[key] = from n in node.Elements() select new DynamicDictionary() { Items = Parse(n) };
                        break;
                    case "dict":
                        ret[key] = new DynamicDictionary() { Items = Parse(node) };
                        break;
                    default:
                        throw new NotSupportedException();
                }
            }
            return ret;
        }

        private static XElement Save(IDictionary<string, object> dict) 
        {
            var node = new XElement("dict");
            foreach (var kv in dict) 
            {
                node.Add(new XElement("key", kv.Key));
                if (kv.Value is string)
                    node.Add(new XElement("string", kv.Value));
                else if (kv.Value is int)
                    node.Add(new XElement("integer", kv.Value));
                else if (kv.Value is bool)
                    node.Add(new XElement(kv.Value.ToString()));
                else if (kv.Value is DateTime)
                    node.Add(new XElement("date", kv.Value));
                else if (kv.Value is byte[])
                    node.Add(new XElement("data", Convert.ToBase64String((byte[])kv.Value)));
                else if (kv.Value is DynamicDictionary)
                    node.Add(Save(((DynamicDictionary)kv.Value).Items));
                else if (kv.Value is IEnumerable<DynamicDictionary>)
                    node.Add(new XElement("array", from x in (IEnumerable<DynamicDictionary>)kv.Value select Save(x.Items)));
            }
            return node;
        }

        public void Save(string file) 
        {
            using (var stream = File.Open(file, FileMode.Create, FileAccess.Write, FileShare.None))
                Save(stream);
        }

        public void Save(Stream stream)
        {
            var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("plist", Save(Items)));
            doc.Save(stream);
        }
    }

  使用方法:

dynamic plist = new Plist(file); //加载plist文件
string key = (string)plist.Key;  //获取值
if(plist.Name == null)               //等于null表示plist文件中不包含节点Name
{
    plist.Name = "esci";             //添加节点Name并赋值为esci
}

plist.Save(file);                        //保存为plist文件

2.解析json

    public class Json : DynamicObject
    {
        private IDictionary<string, object> Dictionary;

        public Json(IDictionary<string, object> dictionary)
        {
            this.Dictionary = dictionary;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this.Dictionary[binder.Name];

            if (result is IDictionary<string, object>)
            {
                this.Dictionary[binder.Name] = result = new Json(result as IDictionary<string, object>);
            }
            else if (result is IEnumerable && !(result is string))
            {
                var list = new List<object>();
                foreach (var i in (result as IEnumerable))
                {
                    if (i is IDictionary<string, object>)
                        list.Add(new Json(i as IDictionary<string, object>));
                    else
                        list.Add(i);
                }
               this.Dictionary[binder.Name] = result = list;
            }

            return true;
        }

        static readonly JavaScriptSerializer jss = new JavaScriptSerializer();

        public static dynamic Deserialize(string json)
        {
            return new Json(jss.Deserialize(json, typeof(object)) as IDictionary<string, object>);
        }

        public static string Serialize(object obj) 
        {
            return jss.Serialize(obj);
        }
    }

  使用方法:

dynamic json = Json.Deserialize(str);
if (json != null)
{
    string msg = json.message;
    ......
}

  

转载于:https://www.cnblogs.com/wmesci/archive/2013/04/19/3031083.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,可以使用第三方库来实现JSON转换为plistplist转换为JSON的功能。 要将JSON转换为plist,可以使用plist-json库。首先,您需要导入该库并使用parse方法将JSON解析plist格式。以下是示例代码: ``` import com.dd.plist.*; import org.json.*; // JSON转换为plist String jsonString = "{\"key\": \"value\"}"; NSDictionary plist = (NSDictionary) PropertyListParser.parse(new JSONTokener(jsonString)); String plistString = plist.toXMLPropertyList(); ``` 在上面的代码中,我们首先定义了一个包含键值对的JSON字符串。然后,使用JSONTokener将其转换为JSON对象。接下来,使用PropertyListParser的parse方法将JSON对象转换为plist对象。最后,使用toXMLPropertyList方法将plist对象转换为plist格式的字符串。 要将plist转换为JSON,您可以使用cocos-pkgjson库。该库可以将.plist文件中的数据提取出来,并生成cocos底层Sprite所需的pkgJson格式。以下是示例代码: ``` import org.json.*; import com.cocos.pkgjson.*; // plist转换为JSON String plistString = "<plist version=\"1.0\"><dict><key>key</key><string>value</string></dict></plist>"; JSONObject json = PkgJsonUtils.plistToJson(plistString); String jsonString = json.toString(); ``` 在上面的代码中,我们定义了一个包含plist格式的字符串。然后,使用PkgJsonUtils的plistToJson方法将plist字符串转换为JSON对象。最后,使用toString方法将JSON对象转换为JSON格式的字符串。 请注意,上述代码仅为示例,您需要根据实际情况进行适当的调整和错误处理。另外,还可以根据具体需求选择其他库或方法来实现JSON转换为plistplist转换为JSON的功能。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [plist-json:将plist转换为json,将json转换为plist,将bplist转换为plist](https://download.csdn.net/download/weixin_42104366/18861762)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [cocos-pkgjson:一个pkgJson工具,将plist文件转换为json数据。 可以将定制的pkgLoader直接使用](https://download.csdn.net/download/weixin_42134878/18536156)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值