Example #1
0
        private static object ReadConfigAsJson(Type type, string folder)
        {
            var ins          = Activator.CreateInstance(type);
            var exportFields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);

            if (exportFields.Length == 0)
            {
                return(ins);
            }
            _serializer.AddConverter(new MyCustomEnumConverter());
            _serializer.AddConverter(new MyDictionaryConverter());
            foreach (var field in exportFields)
            {
                XlsxNameAttribute xlxsName     = (XlsxNameAttribute)Attribute.GetCustomAttribute(field, typeof(XlsxNameAttribute));
                string            jsonFilename = xlxsName != null ? xlxsName.xlsxName : field.Name;
                var file = Path.Combine(folder, jsonFilename + ".json");
                if (!File.Exists(file))
                {
                    throw new Exception(string.Format("xlsx file {0} not exists", jsonFilename));
                }
                Console.WriteLine("read from config: " + jsonFilename);
                FileStream    fs   = File.Open(file, FileMode.Open);
                StringBuilder sb   = new StringBuilder();
                byte[]        b    = new byte[1024];
                UTF8Encoding  temp = new UTF8Encoding(true);

                while (fs.Read(b, 0, b.Length) > 0)
                {
                    sb.Append(temp.GetString(b));
                }
                fs.Close();

                fsData   data;
                fsResult res = fsJsonParser.Parse(sb.ToString(), out data);
                res.AssertSuccess();
                object value = null;
                _serializer.TryDeserialize(data, field.FieldType, ref value).AssertSuccess();
                field.SetValue(ins, value);
            }
            return(ins);
        }