Exemple #1
0
        private static object JsonObjectToDictionary(JsonObject jsonObj, Type type)
        {
            ThrowCastErrorException(jsonObj, JsonObjectType.Object, type);
            var collection = (IDictionary)Activator.CreateInstance(type);
            var types      = TypeUtility.GetElementType(type);
            var keyType    = types[0];
            var valueType  = types[1];

            foreach (var item in jsonObj)
            {
                object key = null;
                //基本数据类型直接转回来
                if (TypeUtility.IsBasicType(keyType))
                {
                    if (TypeUtility.IsEnum(keyType))
                    {
                        key = Enum.Parse(keyType, item.Key.GetString());
                    }
                    else
                    {
                        key = Convert.ChangeType(item.Key.GetString(), keyType);
                    }
                }
                //其他类型由json反序列化回来
                else
                {
                    var valueObj = JsonObjectFactory.CreateJsonObject(item.Key.GetString());
                    key = FromJsonObject(valueObj, keyType);
                }

                var value = FromJsonObject(item.Value, valueType);
                collection[key] = value;
            }

            return(collection);
        }
        private void Start()
        {
            //耗时测试
            var parseJson = TimeTest(() =>
            {
                for (var i = 0; i < 1000; i++)
                {
                    JsonObjectFactory.CreateJsonObject(json);
                }
            });

            Debug.Log("parseJson:" + parseJson);
            var litJson = TimeTest(() =>
            {
#if !UNITY_WSA || UNITY_EDITOR
                for (var i = 0; i < 1000; i++)
                {
                    LitJson.JsonMapper.ToObject(json);
                }
#endif
            });

            Debug.Log("litJson:" + litJson);
            //打印解析的值
            Debug.Log(JsonObjectFactory.CreateJsonObject(json).ToJson());
            Debug.Log(JsonObjectFactory.CreateJsonObject(json, false).ToJson());
            //将解析的出来的再转成json再解析一次
            Debug.Log(JsonObjectFactory
                      .CreateJsonObject(JsonObjectFactory.CreateJsonObject(json).ToJson()).ToJson());
            Debug.Log(JsonObjectFactory
                      .CreateJsonObject(JsonObjectFactory.CreateJsonObject(json, false).ToJson(), false)
                      .ToJson());
            //解析单个值的情况
            Debug.Log(JsonObjectFactory.CreateJsonObject("1").ToJson());
            Debug.Log(JsonObjectFactory.CreateJsonObject("1", false).ToJson());
        }