Read() public method

public Read ( ) : bool
return bool
示例#1
0
        public void DoubleTest()
        {
            string json = @"[ 0.0, -0.0, 3.1416, 8e-3, 7E-5, -128.000009,
                   144e+3, 0.1e2 ]";

            JsonReader reader = new JsonReader (json);
            reader.Read ();

            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 0.0,
                             Double.Epsilon, "A1");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 0.0,
                             Double.Epsilon, "A2");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 3.1416,
                             Double.Epsilon, "A3");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 0.008,
                             Double.Epsilon, "A4");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 0.00007,
                             Double.Epsilon, "A5");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, -128.000009,
                             Double.Epsilon, "A6");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 144000.0,
                             Double.Epsilon, "A7");
            reader.Read ();
            Assert.AreEqual ((double) reader.Value, 10.0,
                             Double.Epsilon, "A8");

            reader.Close ();
        }
示例#2
0
        public void BooleanTest()
        {
            string json = "[ true, false ]";

            JsonReader reader = new JsonReader (json);
            reader.Read ();

            reader.Read ();
            Assert.IsTrue ((bool) reader.Value, "A1");
            reader.Read ();
            Assert.IsTrue (! ((bool) reader.Value), "A2");

            reader.Close ();
        }
示例#3
0
 private void ReadModules(JsonReader reader)
 {
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ArrayEnd) break;
         if (reader.Token == JsonToken.ObjectStart) ReadModule(reader);
     }
 }
示例#4
0
        public static void LitJsonReaderStrings ()
        {
            for (int i = 0; i < Common.Iterations; i++) {
                JsonReader reader = new JsonReader (Common.JsonStrings);

                while (reader.Read ());
            }
        }
示例#5
0
        private static ZenSettings ReadZenSettings(JsonReader reader)
        {
            ZenSettings settings = new ZenSettings();
            Type objType = settings.GetType();

            reader.Read();
            if (reader.Token != JsonToken.ObjectStart)
                return null;

            string currentProp = null;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName)
                    currentProp = reader.Value.ToString();
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    if (currentProp == "variables") settings.variables = ReadHashtable(reader);
                    else settings.langs.Add(currentProp, ReadZenLang(reader));
                }
            }

            foreach (ZenLang lang in settings.langs.Values)
            {
                if (lang.extends != null && settings.langs.ContainsKey(lang.extends))
                    ExtendLang(lang, settings.langs[lang.extends]);
            }

            if (!settings.langs.ContainsKey("xml"))
            {
                ZenLang xlang = new ZenLang();
                xlang.abbreviations = new Hashtable();
                xlang.element_types = new ZenElementTypes(null);
                xlang.filters = "xml, xsl";
                xlang.snippets = new Hashtable();
                settings.langs.Add("xml", xlang);
            }

            settings.variables["child"] = "";
            return settings;
        }
示例#6
0
        public void CommentsTest()
        {
            string json = @"
                {
                    // This is the first property
                    ""foo"" : ""bar"",

                    /**
                     * This is the second property
                     **/
                     ""baz"": ""blah""
                }";

            JsonReader reader = new JsonReader (json);

            reader.Read ();
            reader.Read ();
            Assert.AreEqual ("foo", (string) reader.Value, "A1");

            reader.Read ();
            reader.Read ();
            Assert.AreEqual ("baz", (string) reader.Value, "A2");

            reader.Read ();
            reader.Read ();
            Assert.IsTrue (reader.EndOfJson, "A3");
        }
        public static void WriteJsonData(this JsonWriter writer, JsonData jsonData)
        {
            var reader = new JsonReader(jsonData.ToJson());

            while (reader.Read())
            {
                switch (reader.Token)
                {
                    case JsonToken.None:
                        break;
                    case JsonToken.ObjectStart:
                        writer.WriteObjectStart();
                        break;
                    case JsonToken.PropertyName:
                        writer.WritePropertyName(reader.Value.ToString());
                        break;
                    case JsonToken.ObjectEnd:
                        writer.WriteObjectEnd();
                        break;
                    case JsonToken.ArrayStart:
                        writer.WriteArrayStart();
                        break;
                    case JsonToken.ArrayEnd:
                        writer.WriteArrayEnd();
                        break;
                    case JsonToken.Int:
                        writer.Write((int)reader.Value);
                        break;
                    case JsonToken.Long:
                        writer.Write((long)reader.Value);
                        break;
                    case JsonToken.ULong:
                        writer.Write((ulong)reader.Value);
                        break;
                    case JsonToken.Double:
                        writer.Write((double)reader.Value);
                        break;
                    case JsonToken.String:
                        writer.Write((string)reader.Value);
                        break;
                    case JsonToken.Boolean:
                        writer.Write((bool)reader.Value);
                        break;
                    case JsonToken.Null:
                        break;
                    default:
                        break;
                }
            }
        }
示例#8
0
        public static void ReadArray(JsonReader reader, object context, BeginObjectDelegate begin, ParserDelegate parser, EndObjectDelegate end)
        {
            System.Diagnostics.Debug.Assert(reader.Token == JsonToken.ArrayStart);

            // parse the elements
            reader.Read();
            while (reader.Token != JsonToken.ArrayEnd)
            {
                if (reader.Token == JsonToken.ObjectStart)
                {
                    ReadObject(reader, context, begin, parser, end);
                }
                else if (reader.Token == JsonToken.ArrayStart)
                {
                    ReadArray(reader, context, parser);
                }
                else
                {
                    parser(reader, context);
                }

                reader.Read();
            }
        }
示例#9
0
 private void ReadModule(JsonReader reader)
 {
     // root/modules
     string prop = null;
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd) break;
         if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
         else if (reader.Token == JsonToken.ArrayStart)
         {
             if (prop == "types") ReadTypes(reader);
             else reader.SkipArray();
         }
         else if (reader.Token == JsonToken.ObjectStart) {
             reader.SkipObject();
         }
     }
 }
示例#10
0
        public static void LitJsonReaderFirstProperty ()
        {
            for (int i = 0; i < Common.Iterations; i++) {
                bool found = false;

                JsonReader reader = new JsonReader (Common.JsonText);

                while (reader.Read ()) {
                    if (reader.Token == JsonToken.PropertyName &&
                        (string) reader.Value == "FirstProperty") {
                        found = true;
                        break;
                    }
                }

                if (! found)
                    Console.WriteLine ("FirstProperty not found!");
            }
        }
示例#11
0
 private void Run()
 {
     using (StreamReader sr = new StreamReader(path.Path))
     {
         string raw = sr.ReadToEnd();
         sr.Close();
         JsonReader reader = new JsonReader(raw);
         try
         {
             if (reader.Read() && reader.Token == JsonToken.ObjectStart)
             {
                 files = new Dictionary<string, FileModel>();
                 BuildModel(reader);
                 path.SetFiles(files);
             }
         }
         catch (Exception ex)
         {
             TraceManager.AddAsync(ex.Message);
         }
     }
 }
 public JsonKeyControlLoader(JsonReader reader)
 {
     dummyKeyControl = new DummyKeyControl();
     JsonMapper jsonMapper = new JsonMapper();
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd)
         {
             break;
         }
         if (reader.Token == JsonToken.PropertyName)
         {
             switch (reader.Value as string)
             {
                 case "walkKeyBinding":
                     dummyKeyControl.walkKeyBinding = jsonMapper.ToObject<Dictionary<string, string>>(reader);
                     break;
                 case "layBombKey":
                     dummyKeyControl.layBombKey = jsonMapper.ToObject<string>(reader);
                     break;
             }
         }
     }
 }
示例#13
0
        public JsonWebTokenHeader(string originalData)
        {
            _originalData = originalData;
            var reader = new JsonReader(originalData.Base64UrlDecode(Encoding.UTF8));
            while (reader.Read())
            {
                if (reader.Token == JsonToken.PropertyName)
                {
                    switch (reader.Value.ToString())
                    {
                        case "alg":
                            reader.Read();
                            SetAlgorithm((string)reader.Value);
                            break;
                        case "kid":
                            reader.Read();
                            KeyId = (string)reader.Value;
                            break;
                        case "xdu":
                            reader.Read();
                            KeyFormat = KeyFormat.Rfc4050;
                            KeyUri = new Uri((string)reader.Value);
                            break;
                        case "jku":
                            reader.Read();
                            KeyFormat = KeyFormat.Json;
                            KeyUri = new Uri((string)reader.Value);
                            break;
                        case "xku":
                            reader.Read();
                            KeyFormat = KeyFormat.X509;
                            KeyUri = new Uri((string)reader.Value);
                            break;
                    }
                }

            }
        }
示例#14
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            Type underlying_type = Nullable.GetUnderlyingType(inst_type);
            Type value_type      = underlying_type ?? inst_type;

            if (reader.Token == JsonToken.Null)
            {
                #if NETSTANDARD1_5
                if (inst_type.IsClass() || underlying_type != null)
                {
                    return(null);
                }
                #else
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }
                #endif

                throw new JsonException(String.Format(
                                            "Can't assign null to an instance of type {0}",
                                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();

                if (value_type.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        value_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][value_type];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        value_type))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][value_type];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                #if NETSTANDARD1_5
                if (value_type.IsEnum())
                {
                    return(Enum.ToObject(value_type, reader.Value));
                }
                #else
                if (value_type.IsEnum)
                {
                    return(Enum.ToObject(value_type, reader.Value));
                }
                #endif
                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(value_type, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                list.Clear();

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];

                instance = Activator.CreateInstance(value_type);

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    object property = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        //ÈÃ×ÖµäKey×ÔÊÊÓ¦ÀàÐÍ
                        if (t_data.IsDictionary)
                        {
                            var dicTypes  = instance.GetType().GetGenericArguments();
                            var converter = System.ComponentModel.TypeDescriptor.GetConverter(dicTypes[0]);
                            if (converter != null)
                            {
                                property           = converter.ConvertFromString((string)property);
                                t_data.ElementType = dicTypes[1];
                            }
                        }


                        ((IDictionary)instance).Add(
                            property, ReadValue(
                                t_data.ElementType, reader));
                    }
                }
            }

            return(instance);
        }
示例#15
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            if (reader.Token == JsonToken.Null)
            {
                if (!inst_type.IsClass)
                {
                    throw new JsonException(String.Format(
                                                "Can't assign null to an instance of type {0}",
                                                inst_type));
                }

                return(null);
            }

            //Debug.Log(reader.Token + " " + reader.Value);
            if (reader.Token == JsonToken.Single ||
                reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();

                if (inst_type.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (inst_type.IsEnum)
                {
                    if (json_type.Name == "String")
                    {
                        int re = 0;
                        int.TryParse(reader.Value as string, out re);
                        return(Enum.ToObject(inst_type, re));
                    }
                    else if (json_type.Name == "Boolean")
                    {
                        return(Enum.ToObject(inst_type, ((bool)(reader.Value))?1:0));
                    }

                    return(Enum.ToObject(inst_type, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(inst_type, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                //////////////////////////////////// ADD ////////////////////////////////////
                // ÀàÐÍת»»
                if (inst_type.Name == "String" && json_type.Name != "String")
                {
                    return(reader.Value.ToString());
                }
                else if (json_type.Name == "String")
                {
                    if (inst_type.Name == "Int32")
                    {
                        int re = 0;
                        int.TryParse(reader.Value as string, out re);
                        return(re);
                    }
                    else if (inst_type.Name == "Single")
                    {
                        float re = 0;
                        float.TryParse(reader.Value as string, out re);
                        return(re);
                    }
                    else if (inst_type.Name == "Double")
                    {
                        double re = 0;
                        double.TryParse(reader.Value as string, out re);
                        return(re);
                    }
                    else if (inst_type.Name == "Boolean")
                    {
                        if (reader.Value == "0")
                        {
                            return(false);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
                else if (inst_type.Name == "Int32" && json_type.Name == "Double")
                {
                    return(Convert.ToInt32((double)(reader.Value)));
                }
                else if (inst_type.Name == "Double" && json_type.Name == "Int32")
                {
                    return((double)(reader.Value));
                }
                else if (inst_type.Name == "Single" && json_type.Name == "Double")
                {
                    return(Convert.ToSingle((double)(reader.Value)));
                }
                else if (inst_type.Name == "Single" && json_type.Name == "Int32")
                {
                    return(Convert.ToSingle((int)(reader.Value)));
                }
                else if (inst_type.Name == "Int32" && json_type.Name == "Single")
                {
                    return(Convert.ToInt32((float)(reader.Value)));
                }
                else if (inst_type.Name == "Double" && json_type.Name == "Single")
                {
                    return(Convert.ToDouble((float)(reader.Value)));
                }
                else if (inst_type.Name == "Boolean")
                {
                    return(Convert.ToBoolean(reader.Value));
                }


                NGUIDebug.Log((inst_type.Name == "Boolean") + "  " + (json_type.Name == "String"));
                ////////////////////////////////// ADD OVER /////////////////////////////////
                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type.Name, inst_type.Name));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }

                ////Debug.Log("JsonToken.ArrayStart " + instance.ToString());

                //foreach (var info in list)
                //{
                //    Debug.Log("info = " + info);
                //}
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(inst_type);
                ObjectMetadata t_data = object_metadata[inst_type];

                instance = Activator.CreateInstance(inst_type);

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string property = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                //object obj = ReadValue(prop_data.Type, reader);
                                //Debug.Log("yyy property = " + instance + " " + property + " " + p_info);
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader), //obj,//
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        ((IDictionary)instance).Add(
                            property, ReadValue(
                                t_data.ElementType, reader));
                    }
                }
            }

            return(instance);
        }
示例#16
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            if (reader.Token == JsonToken.Null)
            {
                if (!inst_type.IsClass)
                {
                    throw new JsonException(String.Format(
                                                "Can't assign null to an instance of type {0}",
                                                inst_type));
                }

                return(null);
            }

            /*UnityEngine.Debug.Log (inst_type.ToString());
             * UnityEngine.Debug.Log (reader.Token);*/

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();

                /*Debug.Log (json_type);
                *  Debug.Log (inst_type);*/

                if (inst_type.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (inst_type.IsEnum)
                {
                    return(Enum.ToObject(inst_type, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(inst_type, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item;

                    if (custom_importers_table.ContainsKey(typeof(JsonReader)) &&
                        custom_importers_table[typeof(JsonReader)].ContainsKey(
                            elem_type))
                    {
                        reader.Read();
                        if (reader.Token == JsonToken.ArrayEnd)
                        {
                            break;
                        }

                        ImporterFunc importer =
                            custom_importers_table[typeof(JsonReader)][elem_type];

                        item = importer(reader);
                    }
                    else
                    {
                        item = ReadValue(elem_type, reader);
                    }

                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                if (custom_importers_table.ContainsKey(typeof(string)) &&
                    custom_importers_table[typeof(string)].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[typeof(string)][inst_type];

                    return(importer(reader.Value));
                }

                System.Type init_type = inst_type;
                if (inst_type.IsAbstract)
                {
                    Dictionary <string, System.Type> childTypes = ReflectionUtils.GetChildTypes(inst_type);
                    while (reader.Read() && reader.Token != JsonToken.PropertyName)
                    {
                        ;
                    }

                    if (childTypes.ContainsKey(reader.Value.ToString()))
                    {
                        inst_type = childTypes[reader.Value.ToString()];
                    }
                    else
                    {
                        throw new JsonException(String.Format("Attempting to deserialize JSON of type '{0}'. However, the type '{1}' doesn't inherit from the abstract type '{2}'", inst_type, reader.Value, inst_type));
                    }

                    while (reader.Read() && reader.Token != JsonToken.ObjectStart)
                    {
                        ;
                    }
                }

                //Debug.Log ("This is my type: " + inst_type);
                AddObjectMetadata(inst_type);
                ObjectMetadata t_data = object_metadata[inst_type];

                instance = Activator.CreateInstance(inst_type);

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        if (init_type != inst_type)
                        {
                            while (reader.Read() && reader.Token != JsonToken.ObjectEnd)
                            {
                                ;
                            }
                        }

                        break;
                    }

                    string property = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        Type[] arguments = ((IDictionary)instance).GetType().GetGenericArguments();
                        Type   keyType   = arguments[0];

                        if (keyType == typeof(System.Int32))
                        {
                            ((IDictionary)instance).Add(
                                int.Parse(property), ReadValue(
                                    arguments[1], reader));
                        }
                        else
                        {
                            ((IDictionary)instance).Add(
                                property, ReadValue(
                                    t_data.ElementType, reader));
                        }
                    }
                }
            }

            return(instance);
        }
示例#17
0
 private void ReadInterfaces(JsonReader reader, ClassModel cClass)
 {
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ArrayEnd) break;
         if (reader.Token == JsonToken.String)
         {
             string type = reader.Value.ToString();
             if (cClass.Implements == null) cClass.Implements = new List<string>();
             cClass.Implements.Add(type);
         }
     }
 }
 public static IDictionary<String, object> ReadJsonRpcData(Stream inputStream)
 {
     IDictionary<string, object> data = new Dictionary<string, object>();
     using (StreamReader sr = new StreamReader(inputStream))
     {
         JsonReader reader = new JsonReader(sr);
         reader.Read();
         if (reader.Token != JsonToken.ObjectStart)
             throw new ParseException("Unexpected token read!");
         while (reader.Read())
         {
             if (reader.Token == JsonToken.ObjectEnd)
                 break;
             if (reader.Token != JsonToken.PropertyName)
                 throw new ParseException("Unexpected token read!");
             string field = (string)reader.Value;
             if (!reader.Read())
                 throw new ParseException("Unexpected end of stream!");
             switch (field)
             {
             case "id":
                 data["id"] = (string)reader.Value;
                 break;
             case "method":
                 data["method"] = (string)reader.Value;
                 break;
             case "params":
                 if (reader.Token == JsonToken.ObjectStart)
                 {
                     data["parameters"] = JSON.ReadObject(reader);
                 }
                 break;
             default:
                 break;
             }
         }
     }
     return data;
 }
示例#19
0
        private void DeserializeTable(SerializeTable table, LitJson.JsonReader reader)
        {
            string propertyName = string.Empty;

            while (reader.Read())
            {
                switch (reader.Token)
                {
                case JsonToken.ObjectStart:
                    if (table.Name == propertyName && table.IsRoot)
                    {       // nothing to do
                    }
                    else
                    {
                        DeserializeTable(table.AddChild(propertyName), reader);
                    }
                    //propertyName = string.Empty;
                    break;

                case JsonToken.PropertyName:
                    propertyName = (string)reader.Value;
                    break;

                case JsonToken.ObjectEnd:
                    return;


                case JsonToken.ArrayStart:
                    // for arrary and list
                    DeserializeTable(table.AddChild(propertyName), reader);
                    break;

                case JsonToken.ArrayEnd:
                    // for arrary and list
                    return;

                case JsonToken.Int:
                    //table.AddValue<int>(propertyName, (int)reader.Value);
                    table.AddValue <string>(propertyName, reader.Value.ToString());
                    propertyName = string.Empty;
                    break;

                case JsonToken.Long:
                    //table.AddValue<int>(propertyName, (int)reader.Value);
                    table.AddValue <string>(propertyName, reader.Value.ToString());
                    propertyName = string.Empty;
                    break;

                // case JsonToken.Single:
                //   //table.AddValue<float>(propertyName, (float)reader.Value);
                //   table.AddValue<string>(propertyName, reader.Value.ToString());
                //   propertyName = string.Empty;
                //   break;

                case JsonToken.Double:
                    //table.AddValue<double>(propertyName, (double)reader.Value);
                    table.AddValue <string>(propertyName, reader.Value.ToString());
                    propertyName = string.Empty;
                    break;

                case JsonToken.String:
                    //table.AddValue<string>(propertyName, (string)reader.Value);
                    table.AddValue <string>(propertyName, reader.Value.ToString());
                    propertyName = string.Empty;
                    break;

                case JsonToken.Boolean:
                    //table.AddValue<bool>(propertyName, (bool)reader.Value);
                    table.AddValue <string>(propertyName, reader.Value.ToString());
                    propertyName = string.Empty;
                    break;

                case JsonToken.Null:
                    break;
                }
            }
        }
        // LOOKUP DEFAULT SDK

        private static string GetLatestSDK()
        {
            string path = Environment.ExpandEnvironmentVariables("%USERPROFILE%\\.loom\\loom.config");
            try
            {
                string config = File.ReadAllText(path);
                JsonReader reader = new JsonReader(config);
                if (reader.Read() && reader.Token == JsonToken.ObjectStart)
                    return ReadDefaults(reader);
            }
            catch { }
            return "";
        }
        private static IJsonWrapper ReadValue(WrapperFactory factory,
                                              JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd ||
                reader.Token == JsonToken.Null)
            {
                return(null);
            }

            IJsonWrapper instance = factory();

            if (reader.Token == JsonToken.String)
            {
                instance.SetString((string)reader.Value);
                return(instance);
            }

            if (reader.Token == JsonToken.Double)
            {
                instance.SetDouble((double)reader.Value);
                return(instance);
            }

            if (reader.Token == JsonToken.Int)
            {
                instance.SetInt((int)reader.Value);
                return(instance);
            }

            if (reader.Token == JsonToken.Long)
            {
                instance.SetLong((long)reader.Value);
                return(instance);
            }

            if (reader.Token == JsonToken.Boolean)
            {
                instance.SetBoolean((bool)reader.Value);
                return(instance);
            }

            if (reader.Token == JsonToken.ArrayStart)
            {
                instance.SetJsonType(JsonType.Array);

                while (true)
                {
                    IJsonWrapper item = ReadValue(factory, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    ((IList)instance).Add(item);
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                instance.SetJsonType(JsonType.Object);

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string property = (string)reader.Value;

                    ((IDictionary)instance)[property] = ReadValue(
                        factory, reader);
                }
            }

            return(instance);
        }
示例#22
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type; //Nullable.GetUnderlyingType(inst_type);
            Type value_type      = inst_type;

            if (reader.Token == JsonToken.Null)
            {
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }

                throw new JsonException(String.Format(
                                            "Can't assign null to an instance of type {0}",
                                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();
                var  vt        = value_type is ILRuntime.Reflection.ILRuntimeWrapperType
                    ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR
                    : value_type;

                if (vt.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) ||
                        json_type == typeof(byte))
                    {
                        return(reader.Value);
                    }
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                {
                    return(Enum.ToObject(vt, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(vt, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                if (json_type.IsValueType && vt.IsValueType)
                {
                    if (vt == typeof(int))
                    {
                        return(Convert.ToInt32(reader.Value));
                    }
                    else if (vt == typeof(float))
                    {
                        return((float)Convert.ToDouble(reader.Value));
                    }
                    else if (vt == typeof(double))
                    {
                        return(Convert.ToDouble(reader.Value));
                    }
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType
                        ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType
                        : elem_type;
                    item = rt.CheckCLRTypes(item);
                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                {
                    instance = ((ILRuntime.Reflection.ILRuntimeType)value_type).ILType.Instantiate();
                }
                else
                {
                    if (value_type is ILRuntime.Reflection.ILRuntimeWrapperType)
                    {
                        value_type = ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).RealType;
                    }
                    instance = Activator.CreateInstance(value_type);
                }

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string property = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            var p_prop = ((FieldInfo)prop_data.Info);
                            var value  = ReadValue(prop_data.Type, reader);
                            p_prop.SetValue(instance, value);
                        }
                        else
                        {
                            var p_info = (PropertyInfo)prop_data.Info;
                            var value  = ReadValue(prop_data.Type, reader);
                            p_info.SetValue(instance, value);
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType)t_data.ElementType).RealType
                            : t_data.ElementType;
                        ((IDictionary)instance).Add(
                            property, rt.CheckCLRTypes(ReadValue(
                                                           t_data.ElementType, reader)));
                    }
                }
            }

            return(instance);
        }
示例#23
0
        private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader)
        {
            reader.Read();
            if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null)
            {
                return(null);
            }
            IJsonWrapper jsonWrapper = factory();

            if (reader.Token == JsonToken.String)
            {
                jsonWrapper.SetString((string)reader.Value);
                return(jsonWrapper);
            }
            if (reader.Token == JsonToken.Double)
            {
                jsonWrapper.SetDouble((double)reader.Value);
                return(jsonWrapper);
            }
            if (reader.Token == JsonToken.Int)
            {
                jsonWrapper.SetInt((int)reader.Value);
                return(jsonWrapper);
            }
            if (reader.Token == JsonToken.Long)
            {
                jsonWrapper.SetLong((long)reader.Value);
                return(jsonWrapper);
            }
            if (reader.Token == JsonToken.Boolean)
            {
                jsonWrapper.SetBoolean((bool)reader.Value);
                return(jsonWrapper);
            }
            if (reader.Token == JsonToken.ArrayStart)
            {
                jsonWrapper.SetJsonType(JsonType.Array);
                for (;;)
                {
                    IJsonWrapper value = JsonMapper.ReadValue(factory, reader);
                    if (reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    jsonWrapper.Add(value);
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                jsonWrapper.SetJsonType(JsonType.Object);
                for (;;)
                {
                    reader.Read();
                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }
                    string key = (string)reader.Value;
                    jsonWrapper[key] = JsonMapper.ReadValue(factory, reader);
                }
            }
            return(jsonWrapper);
        }
示例#24
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();
            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }
            if (reader.Token == JsonToken.Null)
            {
                if (!inst_type.IsClass)
                {
                    throw new JsonException(string.Format("Can't assign null to an instance of type {0}", inst_type));
                }
                return(null);
            }
            else
            {
                if (reader.Token != JsonToken.Double && reader.Token != JsonToken.Int && reader.Token != JsonToken.Long && reader.Token != JsonToken.String && reader.Token != JsonToken.Boolean)
                {
                    object obj = null;
                    if (reader.Token == JsonToken.ArrayStart)
                    {
                        JsonMapper.AddArrayMetadata(inst_type);
                        ArrayMetadata arrayMetadata = JsonMapper.array_metadata[inst_type];
                        if (!arrayMetadata.IsArray && !arrayMetadata.IsList)
                        {
                            throw new JsonException(string.Format("Type {0} can't act as an array", inst_type));
                        }
                        IList list;
                        Type  elementType;
                        if (!arrayMetadata.IsArray)
                        {
                            list        = (IList)Activator.CreateInstance(inst_type);
                            elementType = arrayMetadata.ElementType;
                        }
                        else
                        {
                            list        = new ArrayList();
                            elementType = inst_type.GetElementType();
                        }
                        for (;;)
                        {
                            object value = JsonMapper.ReadValue(elementType, reader);
                            if (reader.Token == JsonToken.ArrayEnd)
                            {
                                break;
                            }
                            list.Add(value);
                        }
                        if (arrayMetadata.IsArray)
                        {
                            int count = list.Count;
                            obj = Array.CreateInstance(elementType, count);
                            for (int i = 0; i < count; i++)
                            {
                                ((Array)obj).SetValue(list[i], i);
                            }
                        }
                        else
                        {
                            obj = list;
                        }
                    }
                    else if (reader.Token == JsonToken.ObjectStart)
                    {
                        JsonMapper.AddObjectMetadata(inst_type);
                        ObjectMetadata objectMetadata = JsonMapper.object_metadata[inst_type];
                        obj = Activator.CreateInstance(inst_type);
                        string text;
                        for (;;)
                        {
                            reader.Read();
                            if (reader.Token == JsonToken.ObjectEnd)
                            {
                                break;
                            }
                            text = (string)reader.Value;
                            if (objectMetadata.Properties.ContainsKey(text))
                            {
                                PropertyMetadata propertyMetadata = objectMetadata.Properties[text];
                                if (propertyMetadata.IsField)
                                {
                                    ((FieldInfo)propertyMetadata.Info).SetValue(obj, JsonMapper.ReadValue(propertyMetadata.Type, reader));
                                }
                                else
                                {
                                    PropertyInfo propertyInfo = (PropertyInfo)propertyMetadata.Info;
                                    if (propertyInfo.CanWrite)
                                    {
                                        propertyInfo.SetValue(obj, JsonMapper.ReadValue(propertyMetadata.Type, reader), null);
                                    }
                                    else
                                    {
                                        JsonMapper.ReadValue(propertyMetadata.Type, reader);
                                    }
                                }
                            }
                            else
                            {
                                if (!objectMetadata.IsDictionary)
                                {
                                    goto Block_27;
                                }
                                ((IDictionary)obj).Add(text, JsonMapper.ReadValue(objectMetadata.ElementType, reader));
                            }
                        }
                        return(obj);

Block_27:
                        throw new JsonException(string.Format("The type {0} doesn't have the property '{1}'", inst_type, text));
                    }
                    return(obj);
                }
                Type type = reader.Value.GetType();
                if (inst_type.IsAssignableFrom(type))
                {
                    return(reader.Value);
                }
                if (JsonMapper.custom_importers_table.ContainsKey(type) && JsonMapper.custom_importers_table[type].ContainsKey(inst_type))
                {
                    ImporterFunc importerFunc = JsonMapper.custom_importers_table[type][inst_type];
                    return(importerFunc(reader.Value));
                }
                if (JsonMapper.base_importers_table.ContainsKey(type) && JsonMapper.base_importers_table[type].ContainsKey(inst_type))
                {
                    ImporterFunc importerFunc2 = JsonMapper.base_importers_table[type][inst_type];
                    return(importerFunc2(reader.Value));
                }
                if (inst_type.IsEnum)
                {
                    return(Enum.ToObject(inst_type, reader.Value));
                }
                MethodInfo convOp = JsonMapper.GetConvOp(inst_type, type);
                if (convOp != null)
                {
                    return(convOp.Invoke(null, new object[]
                    {
                        reader.Value
                    }));
                }
                throw new JsonException(string.Format("Can't assign value '{0}' (type {1}) to type {2}", reader.Value, type, inst_type));
            }
        }
示例#25
0
        private static object ReadValue(Type instType, JsonReader reader)
        {
            reader.Read();
            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }
            Type underlyingType = Nullable.GetUnderlyingType(instType);
            Type valueType      = underlyingType ?? instType;

            if (reader.Token == JsonToken.Null)
            {
                        #if JSON_WINRT || (UNITY_METRO && !UNITY_EDITOR)
                /* IsClass is made a getter here as a comparability
                 * patch for WinRT build targets, see Platform.cs */
                if (instType.IsClass() || underlyingType != null)
                {
                        #else
                if (instType.IsClass || underlyingType != null)
                {
                        #endif
                    return(null);
                }
                throw new JsonException(string.Format("Can't assign null to an instance of type {0}", instType));
            }
            if (reader.Token == JsonToken.Real ||
                reader.Token == JsonToken.Natural ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type jsonType = reader.Value.GetType();
                if (valueType.IsAssignableFrom(jsonType))
                {
                    return(reader.Value);
                }
                // Try to find a custom or base importer
                ImporterFunc importer = GetImporter(jsonType, valueType);
                if (importer != null)
                {
                    return(importer(reader.Value));
                }
                // Maybe it's an enum
                        #if JSON_WINRT || (UNITY_METRO && !UNITY_EDITOR)
                /* IsClass is made a getter here as a comparability
                 * patch for WinRT build targets, see Platform.cs */
                if (valueType.IsEnum())
                {
                        #else
                if (valueType.IsEnum)
                {
                        #endif
                    return(Enum.ToObject(valueType, reader.Value));
                }
                // Try using an implicit conversion operator
                MethodInfo convOp = GetConvOp(valueType, jsonType);
                if (convOp != null)
                {
                    return(convOp.Invoke(null, new object[] { reader.Value }));
                }
                // No luck
                throw new JsonException(string.Format("Can't assign value '{0}' (type {1}) to type {2}", reader.Value, jsonType, instType));
            }
            object instance = null;
            if (reader.Token == JsonToken.ArrayStart)
            {
                // If there's a custom importer that fits, use it
                ImporterFunc importer = GetImporter(typeof(JsonData), instType);
                if (importer != null)
                {
                    instType = typeof(JsonData);
                }
                AddArrayMetadata(instType);
                ArrayMetadata tdata = arrayMetadata[instType];
                if (!tdata.IsArray && !tdata.IsList)
                {
                    throw new JsonException(string.Format("Type {0} can't act as an array", instType));
                }
                IList list;
                Type  elemType;
                if (!tdata.IsArray)
                {
                    list     = (IList)CreateInstance(instType);
                    elemType = tdata.ElementType;
                }
                else
                {
                    //list = new ArrayList();
                    list     = new List <object>();
                    elemType = instType.GetElementType();
                }
                while (true)
                {
                    object item = ReadValue(elemType, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    list.Add(item);
                }
                if (tdata.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elemType, n);
                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
                if (importer != null)
                {
                    instance = importer(instance);
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                bool   done     = false;
                string property = null;
                reader.Read();
                if (reader.Token == JsonToken.ObjectEnd)
                {
                    done = true;
                }
                else
                {
                    property = (string)reader.Value;
                    if (reader.TypeHinting && property == reader.HintTypeName)
                    {
                        reader.Read();
                        string typeName = (string)reader.Value;
                        reader.Read();
                        if ((string)reader.Value == reader.HintValueName)
                        {
                            valueType = Type.GetType(typeName);
                            object value = ReadValue(valueType, reader);
                            reader.Read();
                            if (reader.Token != JsonToken.ObjectEnd)
                            {
                                throw new JsonException(string.Format("Invalid type hinting object, has too many properties: {0}...", reader.Token));
                            }
                            return(value);
                        }
                        else
                        {
                            throw new JsonException(string.Format("Expected \"{0}\" property for type hinting but instead got \"{1}\"", reader.HintValueName, reader.Value));
                        }
                    }
                }
                // If there's a custom importer that fits, use to create a JsonData type instead.
                // Once the object is deserialzied, it will be invoked to create the actual converted object.
                ImporterFunc importer = GetImporter(typeof(JsonData), valueType);
                if (importer != null)
                {
                    valueType = typeof(JsonData);
                }
                ObjectMetadata tdata = AddObjectMetadata(valueType);
                instance = CreateInstance(valueType);
                bool firstRun = true;
                while (!done)
                {
                    if (firstRun)
                    {
                        firstRun = false;
                    }
                    else
                    {
                        reader.Read();
                        if (reader.Token == JsonToken.ObjectEnd)
                        {
                            break;
                        }
                        property = (string)reader.Value;
                    }
                    PropertyMetadata pdata;
                    if (tdata.Properties.TryGetValue(property, out pdata))
                    {
                        // Don't deserialize a field or property that has a JsonIgnore attribute with deserialization usage.
                        if ((pdata.Ignore & JsonIgnoreWhen.Deserializing) > 0)
                        {
                            ReadSkip(reader);
                            continue;
                        }
                        if (pdata.IsField)
                        {
                            ((FieldInfo)pdata.Info).SetValue(instance, ReadValue(pdata.Type, reader));
                        }
                        else
                        {
                            PropertyInfo pinfo = (PropertyInfo)pdata.Info;
                            if (pinfo.CanWrite)
                            {
                                pinfo.SetValue(instance, ReadValue(pdata.Type, reader), null);
                            }
                            else
                            {
                                ReadValue(pdata.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!tdata.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(string.Format("The type {0} doesn't have the property '{1}'", instType, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }
                        ((IDictionary)instance).Add(property, ReadValue(tdata.ElementType, reader));
                    }
                }
                if (importer != null)
                {
                    instance = importer(instance);
                }
            }
            return(instance);
        }
示例#26
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type      = inst_type;

            if (reader.Token == JsonToken.Null)
            {
#if NETSTANDARD1_5
                if (inst_type.IsClass() || underlying_type != null)
                {
                    return(null);
                }
#else
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }
#endif

                throw new JsonException(String.Format(
                                            "Can't assign null to an instance of type {0}",
                                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();
                var  vt        = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                    {
                        return(reader.Value);
                    }
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
#if NETSTANDARD1_5
                if (vt.IsEnum())
                {
                    return(Enum.ToObject(vt, reader.Value));
                }
#else
                if (value_type.IsEnum)
                {
                    return(Enum.ToObject(vt, reader.Value));
                }
#endif
                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(vt, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = ( IList )Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                list.Clear();

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = ( int )item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);
                    }
                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        (( Array )instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];

                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                {
                    instance = ((ILRuntime.Reflection.ILRuntimeType)value_type).ILType.Instantiate();
                }
                else
                {
                    instance = Activator.CreateInstance(value_type);
                }

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    object property = ( string )reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            (( FieldInfo )prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                ( PropertyInfo )prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = (( IDictionary )instance);
                        var rt   = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType)t_data.ElementType).RealType
                            : t_data.ElementType;
                        //让字典Key自适应类型
                        if (t_data.IsDictionary)
                        {
                            var dicTypes  = instance.GetType().GetGenericArguments();
                            var converter = System.ComponentModel.TypeDescriptor.GetConverter(dicTypes[0]);
                            if (converter != null)
                            {
                                property = converter.ConvertFromString(( string )property);
                                //对于有自定义类当值的字典类型,需要通过CLRType才能获取到对应的类名
                                t_data.ElementType = dicTypes[1].FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance" ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.GenericArguments[1].Value.ReflectionType : dicTypes[1];
                            }
                        }

                        var readValue      = ReadValue(t_data.ElementType, reader);
                        var checkedCLRType = rt.CheckCLRTypes(readValue);
                        dict.Add(property, checkedCLRType);
                    }
                }
            }

            return(instance);
        }
示例#27
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();
            if (reader.Token == JsonToken.ArrayEnd)
            {
                return((object)null);
            }
            if (reader.Token == JsonToken.Null)
            {
                if (!inst_type.IsClass)
                {
                    throw new JsonException(string.Format("Can't assign null to an instance of type {0}", (object)inst_type));
                }
                return((object)null);
            }
            if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || (reader.Token == JsonToken.Long || reader.Token == JsonToken.String) || reader.Token == JsonToken.Boolean)
            {
                Type type = reader.Value.GetType();
                if (inst_type.IsAssignableFrom(type))
                {
                    return(reader.Value);
                }
                if (JsonMapper.custom_importers_table.ContainsKey(type) && JsonMapper.custom_importers_table[type].ContainsKey(inst_type))
                {
                    return(JsonMapper.custom_importers_table[type][inst_type](reader.Value));
                }
                if (JsonMapper.base_importers_table.ContainsKey(type) && JsonMapper.base_importers_table[type].ContainsKey(inst_type))
                {
                    return(JsonMapper.base_importers_table[type][inst_type](reader.Value));
                }
                if (inst_type.IsEnum)
                {
                    return(Enum.ToObject(inst_type, reader.Value));
                }
                MethodInfo convOp = JsonMapper.GetConvOp(inst_type, type);
                if (!(convOp != (MethodInfo)null))
                {
                    throw new JsonException(string.Format("Can't assign value '{0}' (type {1}) to type {2}", reader.Value, (object)type, (object)inst_type));
                }
                return(convOp.Invoke((object)null, new object[1]
                {
                    reader.Value
                }));
            }
            object obj1 = (object)null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                JsonMapper.AddArrayMetadata(inst_type);
                ArrayMetadata arrayMetadata = JsonMapper.array_metadata[inst_type];
                if (!arrayMetadata.IsArray && !arrayMetadata.IsList)
                {
                    throw new JsonException(string.Format("Type {0} can't act as an array", (object)inst_type));
                }
                IList list;
                Type  elementType;
                if (!arrayMetadata.IsArray)
                {
                    list        = (IList)Activator.CreateInstance(inst_type);
                    elementType = arrayMetadata.ElementType;
                }
                else
                {
                    list        = (IList) new ArrayList();
                    elementType = inst_type.GetElementType();
                }
                while (true)
                {
                    object obj2 = JsonMapper.ReadValue(elementType, reader);
                    if (obj2 != null || reader.Token != JsonToken.ArrayEnd)
                    {
                        list.Add(obj2);
                    }
                    else
                    {
                        break;
                    }
                }
                if (arrayMetadata.IsArray)
                {
                    int count = list.Count;
                    obj1 = (object)Array.CreateInstance(elementType, count);
                    for (int index = 0; index < count; ++index)
                    {
                        ((Array)obj1).SetValue(list[index], index);
                    }
                }
                else
                {
                    obj1 = (object)list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                JsonMapper.AddObjectMetadata(inst_type);
                ObjectMetadata objectMetadata = JsonMapper.object_metadata[inst_type];
                obj1 = Activator.CreateInstance(inst_type);
                string key;
                while (true)
                {
                    reader.Read();
                    if (reader.Token != JsonToken.ObjectEnd)
                    {
                        key = (string)reader.Value;
                        if (objectMetadata.Properties.ContainsKey(key))
                        {
                            PropertyMetadata property = objectMetadata.Properties[key];
                            if (property.IsField)
                            {
                                ((FieldInfo)property.Info).SetValue(obj1, JsonMapper.ReadValue(property.Type, reader));
                            }
                            else
                            {
                                PropertyInfo info = (PropertyInfo)property.Info;
                                if (info.CanWrite)
                                {
                                    info.SetValue(obj1, JsonMapper.ReadValue(property.Type, reader), (object[])null);
                                }
                                else
                                {
                                    JsonMapper.ReadValue(property.Type, reader);
                                }
                            }
                        }
                        else if (!objectMetadata.IsDictionary)
                        {
                            if (reader.SkipNonMembers)
                            {
                                JsonMapper.ReadSkip(reader);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            ((IDictionary)obj1).Add((object)key, JsonMapper.ReadValue(objectMetadata.ElementType, reader));
                        }
                    }
                    else
                    {
                        goto label_45;
                    }
                }
                throw new JsonException(string.Format("The type {0} doesn't have the property '{1}'", (object)inst_type, (object)key));
            }
label_45:
            return(obj1);
        }
示例#28
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type      = inst_type;

            if (reader.Token == JsonToken.Null)
            {
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }

                throw new JsonException(String.Format(
                                            "Can't assign null to an instance of type {0}",
                                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();
                var  vt        = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.FullName.Contains("BindableProperty"))
                {
                    //获取泛型的T
                    string TName       = vt.FullName.Replace("JEngine.Core.BindableProperty`1<", "").Replace(">", "");
                    Type   GenericType = Type.GetType(TName);
                    //强转值到T
                    object[] parameters = new object[1];
                    //泛型赋值的参数
                    parameters[0] = Convert.ChangeType(reader.Value, GenericType);
                    //生成实例且赋值
                    object _instance = Init.Appdomain.Instantiate(vt.FullName, parameters);
                    //返回可绑定数据
                    return(_instance);
                }

                if (vt.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                    {
                        return(reader.Value);
                    }
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                {
                    return(Enum.ToObject(vt, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(vt, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int)item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);
                    }
                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                {
                    instance = ((ILRuntime.Reflection.ILRuntimeType)value_type).ILType.Instantiate();
                }
                else
                {
                    instance = Activator.CreateInstance(value_type);
                }
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string key = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var    dict      = ((IDictionary)instance);
                        var    elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var    rt        = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType)t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var          dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible   = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }
                }
            }

            return(instance);
        }
 private static void ReadDisplay(JsonReader reader)
 {
     string prop = null;
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd) break;
         if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
         else if (reader.Token == JsonToken.String)
         {
             string val = reader.Value.ToString();
             switch (prop)
             {
                 case "width": int.TryParse(val, out proj.MovieOptions.Width); break;
                 case "height": int.TryParse(val, out proj.MovieOptions.Height); break;
             }
         }
         else if (reader.Token == JsonToken.ObjectStart)
         {
             reader.SkipObject();
         }
         else if (reader.Token == JsonToken.ArrayStart)
         {
             reader.SkipArray();
         }
     }
 }
示例#30
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            if (reader.Token == JsonToken.Null)
            {
                if (!inst_type.IsClass)
                {
                    throw new JsonException(String.Format(
                                                "Can't assign null to an instance of type {0}",
                                                inst_type));
                }

                return(null);
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();

                if (inst_type.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        inst_type))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][inst_type];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (inst_type.IsEnum)
                {
                    return(Enum.ToObject(inst_type, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(inst_type, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(inst_type);
                ObjectMetadata t_data = object_metadata[inst_type];

                instance = Activator.CreateInstance(inst_type);

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string property = (string)reader.Value;
                    //Debug.Log("Json property " + property + " in " + inst_type);

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(prop_data.Type, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (reader.IgnoreMissingProperties)
                            {
                                reader.Read();
                                if (reader.Token == JsonToken.ObjectStart || reader.Token == JsonToken.ArrayStart)
                                {
                                    ReadPastCurrentObject(reader);
                                }
                                else
                                {
                                }
                            }
                            else
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'", inst_type, property));
                            }
                        }
                        else
                        {
                            ((IDictionary)instance).Add(
                                property, ReadValue(
                                    t_data.ElementType, reader));
                        }
                    }
                }
            }

            return(instance);
        }
 private static string ReadDefaults(JsonReader reader)
 {
     string prop = null;
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd) break;
         if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
         else if (reader.Token == JsonToken.String)
         {
             string val = reader.Value.ToString();
             switch (prop)
             {
                 case "last_latest": return val; 
             }
         }
         else if (reader.Token == JsonToken.ObjectStart)
         {
             if (prop == "display") ReadDisplay(reader);
             else reader.SkipObject();
         }
         else if (reader.Token == JsonToken.ArrayStart)
         {
             reader.SkipArray();
         }
     }
     return "";
 }
示例#32
0
    public static void ApplyPlayerSettings(ProjectBuildData data)
    {
        Type type = typeof(PlayerSettings);


        var types = typeof(PlayerSettings).GetNestedTypes();

        foreach (var nested in types)
        {
            if (!data.Settings.ContainsKey(nested.Name))
            {
                continue;
            }

            string val    = data.Settings[nested.Name];
            var    reader = new LitJson.JsonReader(val);
            while (reader.Read())
            {
                switch (reader.Token)
                {
                case LitJson.JsonToken.PropertyName:
                {
                    string key = reader.Value.ToString();

                    reader.Read();

                    var info = nested.GetProperty(key);
                    if (info == null || !info.CanWrite)
                    {
                        Debug.LogWarning("ingore property:" + key);
                        continue;
                    }
                    if (info.PropertyType == typeof(string))
                    {
                        info.SetValue(null, reader.Value, null);
                    }
                    else if (info.PropertyType == typeof(bool))
                    {
                        info.SetValue(null, bool.Parse(reader.Value.ToString()), null);
                    }
                    else if (info.PropertyType == typeof(int))
                    {
                        info.SetValue(null, int.Parse(reader.Value.ToString()), null);
                    }
                    else if (info.PropertyType.IsEnum)
                    {
                        info.SetValue(null, Enum.Parse(info.PropertyType, reader.Value.ToString()), null);
                    }
                    else
                    {
                        Debug.LogWarning("unidentifiable property named:" + key + " type:" + info.PropertyType.Name);
                    }

                    break;
                }
                }
            }
        }

        foreach (var col in data.Settings)
        {
            PropertyInfo info = type.GetProperty(col.Key);
            if (info == null || !info.CanWrite)
            {
                Debug.LogWarning("ignore property:" + col.Key);
                continue;
            }

            Debug.LogWarning("set property:" + col.Key);
            if (info.PropertyType == typeof(string))
            {
                info.SetValue(null, col.Value, null);
            }
            else if (info.PropertyType == typeof(bool))
            {
                info.SetValue(null, bool.Parse(col.Value), null);
            }
            else if (info.PropertyType == typeof(int))
            {
                info.SetValue(null, int.Parse(col.Value), null);
            }
            else if (info.PropertyType.IsEnum)
            {
                info.SetValue(null, Enum.Parse(info.PropertyType, col.Value), null);
            }
            else
            {
                Debug.LogWarning("unidentifiable field named:" + col.Key + " type:" + info.PropertyType.Name);
            }
        }

        if (data.Settings.ContainsKey("Icons"))
        {
            string icons            = data.Settings["Icons"];
            var    iconsList        = icons.Split(',');
            var    iconsTextureList = new List <Texture2D>();
            foreach (var str in iconsList)
            {
                var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(str);
                iconsTextureList.Add(texture);
            }

            var group     = GetBuildGroupByTarget(data.Target);
            var iconSizes = PlayerSettings.GetIconSizesForTargetGroup(group);
            if (iconSizes.Length > iconsTextureList.Count)
            {
                int count = iconSizes.Length - iconsTextureList.Count;
                for (int i = 0; i < count; i++)
                {
                    iconsTextureList.Add(null);
                }
            }
            PlayerSettings.SetIconsForTargetGroup(group, iconsTextureList.ToArray());
        }

        ApplySelectedScene(data.Scenes);

        if (data.DebugBuild)
        {
            EditorUserBuildSettings.development     = data.DebugBuild;
            EditorUserBuildSettings.connectProfiler = true;
            EditorUserBuildSettings.allowDebugging  = true;
        }
        else
        {
            EditorUserBuildSettings.development     = false;
            EditorUserBuildSettings.connectProfiler = false;
            EditorUserBuildSettings.allowDebugging  = false;
        }

        PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, data.SymbolDefine);
        PlayerSettings.bundleVersion = data.Version;

        AssetDatabase.Refresh();
    }
示例#33
0
 public override void OnDeserializeTable(SerializeTable rootTable)
 {
     reader.Read();  // read blank node.
     DeserializeTable(rootTable, reader);
 }
示例#34
0
        private MemberModel ReadMethod(JsonReader reader, ClassModel cClass)
        {
            MemberModel member = new MemberModel();
            member.Flags = FlagType.Function;

            string prop = null;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
                else if (reader.Token == JsonToken.String)
                {
                    string val = reader.Value.ToString();
                    switch (prop)
                    {
                        case "name": 
                            if (!val.StartsWith("__op_")) {
                                member.Name = val; 
                                cClass.Members.Add(member); 
                            }
                            break;
                        case "returntype": if (member.Type == null) member.Type = CleanType(val); break;
                        case "docstring": member.Comments = ExtractDoc(val); break;
                    }
                }
                else if (reader.Token == JsonToken.ArrayStart)
                {
                    switch (prop)
                    {
                        case "methodattributes": 
                            ReadAttributes(reader, member); 
                            if ((member.Flags & FlagType.Static) == 0) member.Flags |= FlagType.Dynamic;
                            break;
                        case "parameters": ReadParameters(reader, member); break;
                        case "metainfo": ReadMetas(reader, member); break;
                        default: reader.SkipArray(); break;
                    }
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    switch (prop)
                    {
                        case "templatetypes": ReadTemplateTypes(reader, member); break;
                        default: reader.SkipObject(); break;
                    }
                }
            }
            return member;
        }
示例#35
0
        private void ReadType(JsonReader reader)
        {
            // root/modules/types
            FileModel cFile;
            ClassModel cClass;
            cFile = new FileModel();
            cFile.HasPackage = true;
            cFile.Version = 3;
            cFile.Context = context;
            cClass = new ClassModel();
            cClass.Flags = FlagType.Class;
            MemberModel cDelegate = new MemberModel();
            List<string> names;

            string prop = null;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
                else if (reader.Token == JsonToken.String)
                {
                    string val = reader.Value.ToString();
                    switch (prop)
                    {
                        case "name": cClass.Name = val; break;
                        case "source":
                            if (val.IndexOf('/') > 0) val = val.Substring(val.IndexOf('/') + 1);
                            cFile.FileName = path.Path + "::" + val;
                            break;
                        case "package":
                            if (val.ToLower() == "cocos2d") val = "cocos2d"; // random casing through source
                            cFile.Package = val; 
                            break;
                        case "baseType": cClass.ExtendsType = val; break;
                        case "delegateReturnType": cDelegate.Type = CleanType(val); break;
                        case "type":
                            switch (val)
                            {
                                case "CLASS": break;
                                case "INTERFACE": cClass.Flags |= FlagType.Interface; break;
                                case "STRUCT": cClass.Flags |= FlagType.Struct; break;
                                case "DELEGATE": cDelegate.Name = cClass.Name; break;
                            }
                            break;
                        case "docstring": cClass.Comments = ExtractDoc(val); break;
                    }
                }
                else if (reader.Token == JsonToken.ArrayStart)
                {
                    switch (prop)
                    {
                        case "classattributes": ReadAttributes(reader, cClass); break;
                        case "fields": ReadFields(reader, cClass); break;
                        case "methods": ReadMethods(reader, cClass); break;
                        case "properties": ReadProperties(reader, cClass); break;
                        case "metainfo": ReadMetas(reader, cClass); break;
                        case "imports": 
                            names = ReadNames(reader);
                            foreach (string name in names)
                                cFile.Imports.Add(new MemberModel(name, name, FlagType.Import, Visibility.Public)); 
                            break;
                        case "interfaces": ReadInterfaces(reader, cClass); break;
                        case "delegateTypes":
                            names = ReadNames(reader);
                            if (names.Count > 0)
                            {
                                cDelegate.Parameters = new List<MemberModel>();
                                foreach (string argType in names)
                                {
                                    cDelegate.Parameters.Add(
                                        new MemberModel("p" + cDelegate.Parameters.Count, argType, FlagType.ParameterVar, Visibility.Public));
                                }
                            }
                            break;
                        default: reader.SkipArray(); break;
                    }
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    switch (prop)
                    {
                        case "constructor": 
                            MemberModel ctor = ReadMethod(reader, cClass);
                            cClass.Constructor = ctor.Name;
                            break;
                        default: reader.SkipObject(); break;
                    }
                }
            }

            if (cFile.FileName == null) return;
            string key = cFile.FileName.ToUpper();
            if (files.ContainsKey(key)) cFile = files[key];
            else files.Add(key, cFile);

            if (cFile.Package.ToLower() == "system") // System classes tweaks
            {
                cFile.Package = "";
                if (cClass.Name == "Vector") cClass.Name = "Vector.<T>";
                if (cClass.Name == "Object") cClass.ExtendsType = "void";
            }
            if (cClass.Access == Visibility.Private) cClass.Access = Visibility.Public;

            if (cDelegate.Name != null)
            {
                if (cDelegate.Parameters == null) cDelegate.Parameters = new List<MemberModel>();
                cDelegate.Access = Visibility.Public;
                cDelegate.Flags = FlagType.Function | FlagType.Delegate;
                cDelegate.InFile = cFile;
                cDelegate.IsPackageLevel = true;
                cFile.Members.Add(cDelegate);
            }
            else
            {
                cClass.Type = CleanType(String.IsNullOrEmpty(cFile.Package) ? cClass.Name : cFile.Package + "." + cClass.Name);
                cClass.InFile = cFile;
                cFile.Classes.Add(cClass);
            }
        }
示例#36
0
 private void ReadTemplateTypes(JsonReader reader, MemberModel member)
 {
     string prop = null;
     List<string> names = null;
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd) break;
         if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
         else if (reader.Token == JsonToken.String)
         {
             string val = reader.Value.ToString();
             switch (prop)
             {
                 case "type": member.Type = CleanType(val); break;
             }
         }
         else if (reader.Token == JsonToken.ArrayStart)
         {
             switch (prop)
             {
                 case "types": names = ReadNames(reader); break;
                 default: reader.SkipArray(); break;
             }
         }
     }
     if (names != null) 
         member.Type += ".<" + String.Join(",", names.ToArray()) + ">";
 }
示例#37
0
 private List<String> ReadNames(JsonReader reader)
 {
     List<string> values = new List<string>();
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ArrayEnd) break;
         if (reader.Token == JsonToken.String)
         {
             string val = CleanType(reader.Value.ToString());
             values.Add(val);
         }
     }
     return values;
 }
示例#38
0
        private MemberModel ReadParameter(JsonReader reader, MemberModel member)
        {
            MemberModel para = new MemberModel("???", null, FlagType.Variable | FlagType.ParameterVar, Visibility.Public);
            member.Parameters.Add(para);

            string prop = null;
            bool isRest = false;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
                else if (reader.Token == JsonToken.String)
                {
                    string val = reader.Value.ToString();
                    switch (prop)
                    {
                        case "hasdefault": para.Value = "?"; break; // TODO "hasdefault" is that used?
                        case "isvarargs": isRest = true; break;  // TODO "isvarargs" is that used?
                        case "name": para.Name = val; break;
                        case "type": if (para.Type == null) para.Type = CleanType(val); break;
                    }
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    switch (prop)
                    {
                        case "templatetypes": ReadTemplateTypes(reader, para); break;
                        default: reader.SkipObject(); break;
                    }
                }
            }
            if (isRest) para.Type = "..." + para.Type;
            return para;
        }
示例#39
0
 private void ReadProperties(JsonReader reader, ClassModel cClass)
 {
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ArrayEnd) break;
         if (reader.Token == JsonToken.ObjectStart) ReadProperty(reader, cClass);
     }
 }
示例#40
0
        private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader)
        {
            reader.Read();
            if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null)
            {
                return((IJsonWrapper)null);
            }
            IJsonWrapper jsonWrapper1 = factory();

            if (reader.Token == JsonToken.String)
            {
                jsonWrapper1.SetString((string)reader.Value);
                return(jsonWrapper1);
            }
            if (reader.Token == JsonToken.Double)
            {
                jsonWrapper1.SetDouble((double)reader.Value);
                return(jsonWrapper1);
            }
            if (reader.Token == JsonToken.Int)
            {
                jsonWrapper1.SetInt((int)reader.Value);
                return(jsonWrapper1);
            }
            if (reader.Token == JsonToken.Long)
            {
                jsonWrapper1.SetLong((long)reader.Value);
                return(jsonWrapper1);
            }
            if (reader.Token == JsonToken.Boolean)
            {
                jsonWrapper1.SetBoolean((bool)reader.Value);
                return(jsonWrapper1);
            }
            if (reader.Token == JsonToken.ArrayStart)
            {
                jsonWrapper1.SetJsonType(JsonType.Array);
                while (true)
                {
                    IJsonWrapper jsonWrapper2 = JsonMapper.ReadValue(factory, reader);
                    if (jsonWrapper2 != null || reader.Token != JsonToken.ArrayEnd)
                    {
                        jsonWrapper1.Add((object)jsonWrapper2);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                jsonWrapper1.SetJsonType(JsonType.Object);
                while (true)
                {
                    reader.Read();
                    if (reader.Token != JsonToken.ObjectEnd)
                    {
                        string str = (string)reader.Value;
                        jsonWrapper1[(object)str] = (object)JsonMapper.ReadValue(factory, reader);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(jsonWrapper1);
        }
示例#41
0
        private void ReadProperty(JsonReader reader, ClassModel cClass)
        {
            MemberModel member = new MemberModel();
            member.Flags = FlagType.Variable;

            MemberModel getter = null;
            MemberModel setter = null;
            string prop = null;
            string name = null;
            string doc = null;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
                else if (reader.Token == JsonToken.String)
                {
                    string val = reader.Value.ToString();
                    switch (prop)
                    {
                        case "name": name = val; break;
                        case "docstring": doc = ExtractDoc(val); break;
                    }
                }
                else if (reader.Token == JsonToken.ArrayStart)
                {
                    switch (prop)
                    {
                        //case "propertyattributes": ReadAttributes(reader, member); break;
                        //case "metainfo": reader.SkipArray(); break;
                        default: reader.SkipArray(); break;
                    }
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    switch (prop)
                    {
                        case "getter": 
                            getter = ReadMethod(reader, cClass);
                            getter.Flags |= FlagType.Getter;
                            break;
                        case "setter":
                            setter = ReadMethod(reader, cClass);
                            setter.Flags |= FlagType.Setter;
                            break;
                        default: reader.SkipObject(); break;
                    }
                }
            }
            if (getter != null)
            {
                getter.Name = name;
                getter.Comments = doc;
                getter.Flags &= ~FlagType.Function;
            }
            if (setter != null)
            {
                setter.Name = name;
                if (getter == null) setter.Comments = doc;
                setter.Flags &= ~FlagType.Function;
            }
        }
示例#42
0
        private static ZenLang ReadZenLang(JsonReader reader)
        {
            ZenLang lang = new ZenLang();
            Type objType = lang.GetType();

            string currentProp = null;
            while (reader.Read())
            {
                if (reader.Token == JsonToken.ObjectEnd) break;
                if (reader.Token == JsonToken.PropertyName) currentProp = reader.Value.ToString();
                else if (reader.Token == JsonToken.String)
                {
                    string value = reader.Value.ToString();
                    FieldInfo info = objType.GetField(currentProp);
                    if (info != null) info.SetValue(lang, value);
                }
                else if (reader.Token == JsonToken.ObjectStart)
                {
                    Hashtable table = ReadHashtable(reader);
                    if (currentProp == "element_types")
                    {
                        lang.element_types = new ZenElementTypes(table);
                    }
                    else
                    {
                        FieldInfo info = objType.GetField(currentProp);
                        if (info != null) info.SetValue(lang, table);
                    }
                }
            }
            return lang;
        }
示例#43
0
        private void ReadParameters(JsonReader reader, MemberModel member)
        {
            member.Parameters = new List<MemberModel>();

            while (reader.Read())
            {
                if (reader.Token == JsonToken.ArrayEnd) break;
                if (reader.Token == JsonToken.ObjectStart) ReadParameter(reader, member);
            }
        }
示例#44
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type      = inst_type;

            if (reader.Token == JsonToken.Null)
            {
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }

                throw new JsonException(String.Format(
                                            "Can't assign null to an instance of type {0}",
                                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();
                var  vt        = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                    {
                        return(reader.Value);
                    }
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        vt))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                {
                    return(Enum.ToObject(vt, reader.Value));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(vt, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int)item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);
                    }
                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                {
                    instance = ((ILRuntime.Reflection.ILRuntimeType)value_type).ILType.Instantiate();
                }
                else
                {
                    instance = Activator.CreateInstance(value_type);
                }
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);

                var hotArguments = (inst_type as ILRuntimeWrapperType)?.CLRType.GenericArguments?
                                   .Select(i => i.Value)
                                   .ToList()
                                   .FindAll(t => !(t is CLRType));

                var valid = hotArguments?.Count == 1;

                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string key = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            var val      = ((FieldInfo)prop_data.Info);
                            var realType = prop_data.Type;
                            if (val.FieldType.ToString() == "ILRuntime.Runtime.Intepreter.ILTypeInstance")
                            {
                                //支持一下本地泛型<热更类型>,这种属于CLRType,会new ILTypeIns导致错误
                                //这里要做的就是把泛型参数里面的热更类型获取出来
                                //但如果有超过1个热更类型在参数里,就没办法判断哪个是这个字段的ILTypeIns了,所以只能1个
                                if (!valid)
                                {
                                    throw new NotSupportedException("仅支持解析1个热更类型做泛型参数的本地泛型类");
                                }

                                realType = hotArguments[0].ReflectionType;
                            }

                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, ReadValue(realType, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            var val      = ((PropertyInfo)prop_data.Info);
                            var realType = prop_data.Type;
                            if (val.PropertyType.ToString() == "ILRuntime.Runtime.Intepreter.ILTypeInstance")
                            {
                                if (!valid)
                                {
                                    throw new NotSupportedException("仅支持解析1个热更类型做泛型参数的本地泛型类");
                                }

                                realType = hotArguments[0].ReflectionType;
                            }

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    ReadValue(realType, reader),
                                    null);
                            }
                            else
                            {
                                ReadValue(realType, reader);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var    dict      = ((IDictionary)instance);
                        var    elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var    rt        = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType)t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var          dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible   = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }
                }
            }

            return(instance);
        }
示例#45
0
 private void ReadAttributes(JsonReader reader, MemberModel decl)
 {
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ArrayEnd) break;
         if (reader.Token == JsonToken.String)
         {
             string val = reader.Value.ToString();
             switch (val)
             {
                 case "native": decl.Flags |= FlagType.Native; break;
                 case "static": decl.Flags |= FlagType.Static; break;
                 case "public": decl.Access |= Visibility.Public; break;
                 case "internal": decl.Access |= Visibility.Internal; break;
                 case "protected": decl.Access |= Visibility.Protected; break;
                 case "private": decl.Access |= Visibility.Private; break;
                 case "final": decl.Flags |= FlagType.Final; break;
                 case "operator": break;
                 case "supercall": break;
                 default: break;
             }
         }
     }
 }
        // READ PROJECT'S LOOM.CONFIG

        private static void UpdateProject()
        {
            try
            {
                string config = File.ReadAllText(configPath);
                JsonReader reader = new JsonReader(config);
                if (reader.Read() && reader.Token == JsonToken.ObjectStart)
                    ReadConfig(reader);
            }
            catch (Exception ex)
            {
                TraceManager.AddAsync("Unable to read Loom config '" + configPath + "':\n" + ex.Message);
            }
        }
 private static void ReadConfig(JsonReader reader)
 {
     string prop = null;
     while (reader.Read())
     {
         if (reader.Token == JsonToken.ObjectEnd) break;
         if (reader.Token == JsonToken.PropertyName) prop = reader.Value.ToString();
         else if (reader.Token == JsonToken.String)
         {
             string val = reader.Value.ToString();
             switch (prop)
             {
                 case "sdk_version":
                     if (val == "latest") val = GetLatestSDK();
                     proj.PreferredSDK = val + ";;"; break;
             }
         }
         else if (reader.Token == JsonToken.ObjectStart)
         {
             if (prop == "display") ReadDisplay(reader);
             else reader.SkipObject();
         }
         else if (reader.Token == JsonToken.ArrayStart)
         {
             reader.SkipArray();
         }
     }
 }
示例#48
0
        private static object ReadValue(Type inst_type, JsonReader reader)
        {
            reader.Read();

            if (reader.Token == JsonToken.ArrayEnd)
            {
                return(null);
            }

            Type underlying_type = Nullable.GetUnderlyingType(inst_type);
            Type value_type      = underlying_type ?? inst_type;

            if (reader.Token == JsonToken.Null)
            {
                if (inst_type.IsClass || underlying_type != null)
                {
                    return(null);
                }
                if (inst_type == typeof(Int32))
                {
                    return(0);
                }
                else if (inst_type == typeof(String))
                {
                    return("");
                }
                return(null);
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean)
            {
                Type json_type = reader.Value.GetType();

                if (value_type.IsAssignableFrom(json_type))
                {
                    return(reader.Value);
                }

                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey(json_type) &&
                    custom_importers_table[json_type].ContainsKey(
                        value_type))
                {
                    ImporterFunc importer =
                        custom_importers_table[json_type][value_type];

                    return(importer(reader.Value));
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey(json_type) &&
                    base_importers_table[json_type].ContainsKey(
                        value_type))
                {
                    ImporterFunc importer =
                        base_importers_table[json_type][value_type];

                    return(importer(reader.Value));
                }

                // Maybe it's an enum
                if (value_type.IsEnum)
                {
                    return(Enum.Parse(value_type, reader.Value.ToString()));
                }

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp(value_type, json_type);

                if (conv_op != null)
                {
                    return(conv_op.Invoke(null,
                                          new object[] { reader.Value }));
                }

                // No luck
                throw new JsonException(String.Format(
                                            "Can't assign value '{0}' (type {1}) to type {2}",
                                            reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart)
            {
                AddArrayMetadata(inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (!t_data.IsArray && !t_data.IsList)
                {
                    throw new JsonException(String.Format(
                                                "Type {0} can't act as an array",
                                                inst_type));
                }

                IList list;
                Type  elem_type;

                if (!t_data.IsArray)
                {
                    list      = (IList)Activator.CreateInstance(inst_type);
                    elem_type = t_data.ElementType;
                }
                else
                {
                    list      = new ArrayList();
                    elem_type = inst_type.GetElementType();
                }

                while (true)
                {
                    object item = ReadValue(elem_type, reader);
                    if (item is IJsonReader)
                    {
                        ((IJsonReader)item).OnJsonToObjectFinished();
                    }

                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                    {
                        break;
                    }

                    list.Add(item);
                }

                if (t_data.IsArray)
                {
                    int n = list.Count;
                    instance = Array.CreateInstance(elem_type, n);

                    for (int i = 0; i < n; i++)
                    {
                        ((Array)instance).SetValue(list[i], i);
                    }
                }
                else
                {
                    instance = list;
                }
            }
            else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);

                ObjectMetadata t_data = object_metadata[value_type];
                try
                {
                    instance = Activator.CreateInstance(value_type);
                }
                catch (System.Exception e)
                {
                    UnityEngine.Debug.LogError(inst_type.ToString() + " convert failed");
                }


                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                    {
                        break;
                    }

                    string property = (string)reader.Value;

                    if (t_data.Properties.ContainsKey(property))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[property];
                        object item = ReadValue(prop_data.Type, reader);
                        if (item is IJsonReader)
                        {
                            ((IJsonReader)item).OnJsonToObjectFinished();
                        }
                        if (prop_data.IsField)
                        {
                            ((FieldInfo)prop_data.Info).SetValue(
                                instance, item);
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo)prop_data.Info;

                            if (p_info.CanWrite)
                            {
                                p_info.SetValue(
                                    instance,
                                    item,
                                    null);
                            }
                        }
                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {
                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                                            "The type {0} doesn't have the " +
                                                            "property '{1}'",
                                                            inst_type, property));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }
                        Type   keytype = value_type.GenericTypeArguments[0];
                        object value   = ReadValue(
                            value_type.GenericTypeArguments[1], reader);
                        if (value is IJsonReader)
                        {
                            ((IJsonReader)value).OnJsonToObjectFinished();
                        }
                        if (keytype.IsEnum)
                        {
                            ((IDictionary)instance).Add(
                                Enum.Parse(keytype, property), value);
                        }
                        else if (keytype == typeof(int))
                        {
                            ((IDictionary)instance).Add(Convert.ToInt32(property), value);
                        }
                        else
                        {
                            ((IDictionary)instance).Add(
                                property, value);
                        }
                    }
                }
            }

            return(instance);
        }