コード例 #1
0
 public override Dictionary <string, string> EnumOptions(object target, string paramName)
 {
     if (target.GetType() == typeof(PackBundleSetting))
     {
         //打包//
         JsonFieldTypes pc = JsonFieldAttribute.GetFieldFlag(target, paramName);
         if (pc != JsonFieldTypes.Null)
         {
             if (pc == JsonFieldTypes.PackType)
             {
                 //分包方式//
                 return(GOEPackV5.msArrayPackType);
             }
         }
     }
     return(null);
 }
コード例 #2
0
            public T ToInstance <T>(string json) where T : new()
            {
                Dictionary <string, string> dic = new Dictionary <string, string>();

                string[] fields = json.Replace("{", "").Replace("}", "").Split(',');
                for (int i = 0; i < fields.Length; i++)
                {
                    string[] keyvalue = fields[i].Split(':');
                    dic.Add(Filter(keyvalue[0]), Filter(keyvalue[1]));
                }

                PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                T entity = new T();

                foreach (PropertyInfo property in properties)
                {
                    object[] propertyAttrs = property.GetCustomAttributes(false);
                    for (int i = 0; i < propertyAttrs.Length; i++)
                    {
                        object propertyAttr = propertyAttrs[i];
                        if (propertyAttr is JsonFieldAttribute)
                        {
                            JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;
                            foreach (KeyValuePair <string, string> item in dic)
                            {
                                if (item.Key == jsonFieldAttribute.Name)
                                {
                                    Type t = property.PropertyType;
                                    property.SetValue(entity, ToType(t, item.Value), null);
                                    break;
                                }
                            }
                        }
                    }
                }
                return(entity);
            }
コード例 #3
0
        public static JsonSchemaAttribute CreateFromType(Type ty, JsonSchemaRegistory reg = null, bool asRef = false)
        {
            var kind = Node.KindOfType(ty);

            switch (kind)
            {
            case NodeKind.Boolean:
                return(new JsonSchemaAttribute
                {
                    Type = "boolean",
                });

            case NodeKind.Integer:
                object[] enumsForInteger = null;
                if (TypeHelper.TypeWrap(ty).IsEnum)
                {
                    enumsForInteger = System.Enum.GetValues(ty).Cast <object>().ToArray();
                }
                return(new JsonSchemaAttribute
                {
                    Type = "integer",
                    Enum = enumsForInteger,
                });

            case NodeKind.Float:
                return(new JsonSchemaAttribute
                {
                    Type = "number",
                });

            case NodeKind.String:
                object[] enumsForString = null;
                if (TypeHelper.TypeWrap(ty).IsEnum)
                {
                    enumsForString = TypeHelper.GetStringEnumNames(ty);
                }
                return(new JsonSchemaAttribute
                {
                    Type = "string",
                    Enum = enumsForString,
                });

            case NodeKind.Array:
                var elemTy = TypeHelper.ElemTypeOfIEnumerable(ty);
                return(new JsonSchemaAttribute
                {
                    Type = "array",
                    Items = elemTy != null?CreateFromType(elemTy, reg, true) : null,
                });

            case NodeKind.Object:
                if (ty == typeof(object))
                {
                    return(new JsonSchemaAttribute());
                }

                if (TypeHelper.TypeWrap(ty).IsGenericType&& ty.GetGenericTypeDefinition() == typeof(Dictionary <,>))
                {
                    return(new JsonSchemaAttribute
                    {
                        Type = "object",
                    });
                }

                break;

            default:
                throw new NotImplementedException();
            }

            if (reg == null)
            {
                reg = JsonSchemaRegistory.GetDefault();
            }

            var schema = TypeHelper.GetCustomAttribute <JsonSchemaAttribute>(ty);

            if (schema == null)
            {
                schema = new JsonSchemaAttribute();
            }
            schema.Type = "object";

            var schemaId = schema.Id;

            if (schemaId == null)
            {
                schemaId = ty.ToString();
            }
            var refSchema = reg.Resolve(schemaId);

            if (refSchema != null)
            {
                schema = refSchema;
                goto skip;
            }
            else
            {
                reg.Register(schemaId, schema);
            }

            var baseType = TypeHelper.TypeWrap(ty).BaseType;
            HashSet <string> baseFieldNames = null;

            if (baseType != null)
            {
                Type schemaBaseType;
                if (RefChecker.IsRefTag(baseType, out schemaBaseType))
                {
                    var baseSchemaValue = CreateFromType(schemaBaseType, reg, false);
                    schema.Type = baseSchemaValue.Type;

                    goto skip;
                }

                // Nest fields included in the base class
                var baseSchema = CreateFromType(baseType, reg, true);
                if (baseSchema != null && baseSchema.Ref != null)
                {
                    schema.AddToAllOf(baseSchema);

                    var baseFields = TypeHelper.TypeWrap(baseType).GetFields(BindingFlags.Public | BindingFlags.Instance);
                    baseFieldNames = new HashSet <string>(baseFields.Select(f => f.Name));
                }
            }

            var properties   = new Dictionary <string, JsonSchemaAttribute>();
            var required     = new List <string>();
            var dependencies = new Dictionary <string, string[]>();

            var fields = TypeHelper.TypeWrap(ty).GetFields(BindingFlags.Public | BindingFlags.Instance);

            foreach (var field in fields)
            {
                var fieldType = field.FieldType;

                JsonSchemaAttribute fieldSchema = null;
                var attr     = TypeHelper.GetCustomAttribute <JsonFieldAttribute>(field);
                var elemName = JsonFieldAttribute.FieldName(attr, field); // TODO: duplication check

                // If elements are also included in Base classes, skip collecting a schema for the elements.
                if (baseFieldNames != null && baseFieldNames.Contains(field.Name))
                {
                    fieldSchema = new JsonSchemaAttribute();
                    goto skipField;
                }

                fieldSchema = TypeHelper.GetCustomAttribute <JsonSchemaAttribute>(field);
                if (fieldSchema == null)
                {
                    fieldSchema = new JsonSchemaAttribute();
                }

                var fieldItemsSchema = TypeHelper.GetCustomAttribute <ItemsJsonSchemaAttribute>(field);
                if (fieldItemsSchema != null)
                {
                    fieldSchema.Items = fieldItemsSchema;
                }

                if (attr != null && attr.DynamicResolverTag != null)
                {
                    if (!TypeHelper.TypeWrap(fieldType).IsGenericType || fieldType.GetGenericTypeDefinition() != typeof(Dictionary <,>))
                    {
                        var baseMsg = "A type of the field which has DynamicResolver must be a Dictionary<,>";
                        var msg     = string.Format("{0}: Type = {1} at \"{2}\" of {3}", baseMsg, fieldType, elemName, ty);
                        throw new ArgumentException(msg);
                    }

                    var keyType = TypeHelper.TypeWrap(fieldType).GetGenericArguments()[0];
                    if (keyType != typeof(string))
                    {
                        var baseMsg = "A key of the dictionary which has DynamicResolver must be a string type";
                        var msg     = string.Format("{0}: KeyType = {1} at \"{2}\" of {3}", baseMsg, keyType, elemName, ty);
                        throw new ArgumentException(msg);
                    }

                    fieldSchema._dynamicResolverTag = attr.DynamicResolverTag;
                }

                var fieldItemRequired = TypeHelper.GetCustomAttribute <JsonSchemaRequiredAttribute>(field);
                if (fieldItemRequired != null)
                {
                    required.Add(elemName);
                }

                var fieldItemDependencies = TypeHelper.GetCustomAttribute <JsonSchemaDependenciesAttribute>(field);
                if (fieldItemDependencies != null)
                {
                    dependencies.Add(elemName, fieldItemDependencies.Dependencies);
                }

                var fieldTypeSchema = CreateFromType(fieldType, reg, true);
                if (fieldTypeSchema.Ref != null)
                {
                    fieldSchema = fieldTypeSchema;
                }
                else
                {
                    // Update
                    if (fieldSchema.Type == null)
                    {
                        fieldSchema.Type = fieldTypeSchema.Type;
                    }

                    if (fieldSchema.Enum == null)
                    {
                        fieldSchema.Enum = fieldTypeSchema.Enum;
                    }

                    if (fieldTypeSchema.Items != null)
                    {
                        var fieldTypeSchemaItems = fieldTypeSchema.Items as JsonSchemaAttribute;
                        if (fieldTypeSchemaItems.Ref != null)
                        {
                            fieldSchema.Items = fieldTypeSchemaItems;
                        }
                        else
                        {
                            if (fieldTypeSchemaItems.Type != null)
                            {
                                var fieldSchemaItems = fieldSchema.Items as JsonSchemaAttribute;
                                if (fieldSchemaItems != null)
                                {
                                    fieldSchemaItems.Type = fieldTypeSchemaItems.Type;
                                }
                                else
                                {
                                    fieldSchema.Items = new JsonSchemaAttribute
                                    {
                                        Type = fieldTypeSchemaItems.Type,
                                    };
                                }
                            }

                            if (fieldTypeSchemaItems.Enum != null)
                            {
                                var fieldSchemaItems = fieldSchema.Items as JsonSchemaAttribute;
                                fieldSchemaItems.Enum = fieldTypeSchemaItems.Enum;
                            }
                        }
                    }
                }

                // Add custom refs to AllOf not to override constrains which already existing.
                var customRef = TypeHelper.GetCustomAttribute <JsonSchemaRefAttribute>(field);
                if (customRef != null)
                {
                    Type schemaBaseType;
                    if (!RefChecker.IsRefTagDerived(customRef.TagType, out schemaBaseType))
                    {
                        throw new ArgumentException("IRefTag<T> must be derived by tagType");
                    }

                    var customSchema = CreateFromType(customRef.TagType, reg, true);
                    switch (customRef.Influence)
                    {
                    case InfluenceRange.Entiry:
                        fieldSchema.AddToAllOf(customSchema);
                        break;

                    case InfluenceRange.AdditionalProperties:
                        if (fieldSchema.AdditionalProperties == null)
                        {
                            fieldSchema.AdditionalProperties = new JsonSchemaAttribute();
                        }
                        fieldSchema.AdditionalProperties.AddToAllOf(customSchema);
                        break;
                    }
                }

                // Add custom refs to AllOf not to override constrains which already existing.
                var customItemsRef = TypeHelper.GetCustomAttribute <ItemsJsonSchemaRefAttribute>(field);
                if (customItemsRef != null)
                {
                    Type schemaBaseType;
                    if (!RefChecker.IsRefTagDerived(customItemsRef.TagType, out schemaBaseType))
                    {
                        throw new ArgumentException("IRefTag<T> must be derived by tagType");
                    }

                    var customSchema = CreateFromType(customItemsRef.TagType, reg, true);
                    switch (customItemsRef.Influence)
                    {
                    case InfluenceRange.Entiry:
                        if (fieldSchema.Items == null)
                        {
                            fieldSchema.Items = new JsonSchemaAttribute();
                        }
                        ((JsonSchemaAttribute)fieldSchema.Items).AddToAllOf(customSchema);
                        break;

                    case InfluenceRange.AdditionalProperties:
                        if (fieldSchema.Items == null)
                        {
                            fieldSchema.Items = new JsonSchemaAttribute();
                        }
                        if (((JsonSchemaAttribute)fieldSchema.Items).AdditionalProperties == null)
                        {
                            ((JsonSchemaAttribute)fieldSchema.Items).AdditionalProperties =
                                new JsonSchemaAttribute();
                        }
                        ((JsonSchemaAttribute)fieldSchema.Items).AdditionalProperties.AddToAllOf(customSchema);
                        break;
                    }
                }

skipField:
                properties.Add(elemName, fieldSchema);
            }

            schema.Properties = properties;
            if (required.Count != 0)
            {
                schema.Required = required.ToArray();
            }
            if (dependencies.Count != 0)
            {
                schema.Dependencies = dependencies;
            }

skip:
            if (asRef)
            {
                return(new JsonSchemaAttribute
                {
                    Ref = schemaId,
                });
            }

            return(schema);
        }
コード例 #4
0
        void MakeStringInterfaceUIInternal(object si, int indentLevel)
        {
            if (null == si)
            {
                return;
            }
            //缩进//
            EditorGUI.indentLevel = indentLevel;
            //列出SI类型//
            if (!m_FoldOutMap.ContainsKey(si))
            {
                m_FoldOutMap.Add(si, true);
            }
            //m_SIFoldOutMap[si] = EditorGUILayout.Foldout(m_SIFoldOutMap[si], si.getParamDictionary().getName());
            object[] typeAttr = si.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false);
            string   typeName = typeAttr.Length > 0 ? ((DisplayNameAttribute)typeAttr[0]).DisplayName : si.GetType().FullName;

            m_FoldOutMap[si] = EditorGUILayout.Foldout(m_FoldOutMap[si], typeName);
            if (m_FoldOutMap[si])
            {
                //列出SI属性//
                EditorGUI.indentLevel = indentLevel + 1;
                foreach (PropertyInfo pd in JsonUtil.GetProperties(si))
                {
                    if (JsonFieldAttribute.GetFieldFlag(si, pd.Name) == JsonFieldTypes.HasChildren)
                    {
                        IEnumerable sis = pd.GetValue(si, null) as IEnumerable;
                        foreach (object ssi in sis)
                        {
                            MakeStringInterfaceUIInternal(ssi, indentLevel + mcnIndentStep);
                        }
                        continue;
                    }

                    if (!pd.CanWrite || !pd.CanRead)
                    {
                        continue;
                    }

                    if (JsonFieldAttribute.GetFieldFlag(si, pd.Name) == JsonFieldTypes.UnEditable)
                    {
                        continue;
                    }


                    GUILayout.BeginHorizontal();
                    object value = pd.GetValue(si, null);

                    //否则按类型创建控件//
                    string   fieldDisName;
                    object[] atts = pd.GetCustomAttributes(typeof(DisplayNameAttribute), false);
                    fieldDisName = atts.Length > 0 ? ((DisplayNameAttribute)atts[0]).DisplayName : pd.Name;
                    if (pd.PropertyType == typeof(bool))
                    {
                        bool v = (bool)value;
                        v     = EditorGUILayout.Toggle(fieldDisName, v);
                        value = v;
                    }
                    else if (pd.PropertyType == typeof(float))
                    {
                        float v = (float)value;
                        v     = EditorGUILayout.FloatField(fieldDisName, v);
                        value = v;
                    }
                    else if (pd.PropertyType == typeof(int))
                    {
                        int v = (int)value;
                        v     = EditorGUILayout.IntField(fieldDisName, v);
                        value = v;
                    }
                    else if (pd.PropertyType == typeof(double))
                    {
                        double v = (double)value;
                        v     = (double)EditorGUILayout.FloatField(fieldDisName, (float)v);
                        value = v;
                    }
                    else if (pd.PropertyType == typeof(Color))
                    {
                        Color color = (Color)value;
                        color = EditorGUILayout.ColorField(fieldDisName, color);
                        value = color;
                    }
                    else if (pd.PropertyType == typeof(string[]))
                    {
                        string v = value != null?JsonUtil.StringArrayToString(value as string[]) : "";

                        v     = EditorGUILayout.TextField(fieldDisName, v);
                        value = JsonUtil.StringToStringArray(v);
                    }
                    else if (pd.PropertyType == typeof(int[]))
                    {
                        string v = JsonUtil.ArrayToString(value as int[]);
                        v     = EditorGUILayout.TextField(fieldDisName, v);
                        value = JsonUtil.StringToArray <int>(v);
                    }
                    else if (pd.PropertyType == typeof(double[]))
                    {
                        /*  string v = JsonUtil.ArrayToString(value as double[]);
                         * v = EditorGUILayout.TextField(fieldDisName, v);
                         * if (GUILayout.Button("拾取", GUILayout.Width(100)))
                         * {
                         *    Vector3 pos = Vector3.zero;
                         *    if ((value as double[]).Length == 3)
                         *        pos = new Vector3((float)(value as double[])[0], (float)(value as double[])[1], (float)(value as double[])[2]);
                         *    PositionPicker picker = PositionPickerTool.PickPosition(pos, si, pd, true);
                         * }
                         * value = JsonUtil.StringToArray<double>(v);*/
                    }
                    else if (pd.PropertyType == typeof(float[]))
                    {
                        /* string v = JsonUtil.ArrayToString(value as float[]);
                         * v = EditorGUILayout.TextField(fieldDisName, v);
                         * if (GUILayout.Button("拾取", GUILayout.Width(100)))
                         * {
                         *   Vector3 pos = Vector3.zero;
                         *   if ((value as float[]).Length == 3)
                         *       pos = new Vector3((value as float[])[0], (value as float[])[1], (value as float[])[2]);
                         *   PositionPicker picker = PositionPickerTool.PickPosition(pos, si, pd, true);
                         * }
                         * value = JsonUtil.StringToArray<float>(v);*/
                    }
                    else if (pd.PropertyType == typeof(Vector3))
                    {
                        Vector3 v = (Vector3)value;
                        v     = EditorGUILayout.Vector3Field(fieldDisName, v);
                        value = v;
                    }
                    else
                    {
                        string v = string.Empty;
                        if (value != null)
                        {
                            v = value.ToString();
                        }
                        v     = EditorGUILayout.TextField(fieldDisName, v);
                        value = v;
                    }
                    Dictionary <string, string> options = m_CurStringInterfaceHelper.EnumOptions(si, pd.Name);
                    if (null != options && options.Count > 0)
                    {
                        //如有枚举选项则创建选项下拉框//
                        int      idx         = -1;
                        string[] name        = new string[options.Count];
                        string[] displayName = new string[options.Count];

                        int j = 0;
                        foreach (KeyValuePair <string, string> i in options)
                        {
                            name[j]          = i.Key;
                            displayName[j++] = i.Value;
                        }

                        for (int i = 0; i < name.Length; i++)
                        {
                            if (name[i] == value.ToString())
                            {
                                idx = i;
                            }
                        }
                        const int popupWidth = 100;

                        idx = EditorGUILayout.Popup(idx, displayName, GUILayout.Width(popupWidth));
                        if (idx != -1)
                        {
                            value = JsonUtil.ConvertData(name[idx], pd.PropertyType);
                        }
                    }
                    //Debug.Log(value);
                    pd.SetValue(si, value, null);
                    GUILayout.EndHorizontal();
                }
            }
            //缩进//
            EditorGUI.indentLevel = indentLevel;
        }