浏览代码

Unknown enum support

Brad Robinson 9 年之前
父节点
当前提交
e3e6ee2ec0
共有 1 个文件被更改,包括 44 次插入1 次删除
  1. 44 1
      PetaJson.cs

+ 44 - 1
PetaJson.cs

@@ -598,6 +598,34 @@ namespace PetaJson
         }
     }
 
+
+	// Apply to enum values to specify which enum value to select
+	// if the supplied json value doesn't match any.
+	// If not found throws an exception
+	// eg, any unknown values in the json will be mapped to Fruit.unknown
+	//
+	//	 [JsonUnknown(Fruit.unknown)]
+	//   enum Fruit
+	//   {
+	// 		unknown,
+	//      Apple,
+	//      Pear,
+	//	 }
+	[AttributeUsage(AttributeTargets.Enum)]
+	public class JsonUnknownAttribute : Attribute
+	{
+		public JsonUnknownAttribute(object unknownValue)
+		{
+			UnknownValue = unknownValue;
+		}
+
+		public object UnknownValue
+		{
+			get;
+			private set;
+		}
+	}
+
     namespace Internal
     {
         public enum Token
@@ -829,7 +857,22 @@ namespace PetaJson
                     if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
                         return ReadLiteral(literal => Enum.ToObject(type, literal));
                     else
-                        return ReadLiteral(literal => Enum.Parse(type, (string)literal));
+						return ReadLiteral(literal => {
+							
+							try
+							{
+								return Enum.Parse(type, (string)literal);
+							}
+							catch (Exception x)
+							{
+								var attr = type.GetCustomAttributes(typeof(JsonUnknownAttribute), false).FirstOrDefault();
+								if (attr==null)
+									throw x;
+
+								return ((JsonUnknownAttribute)attr).UnknownValue;
+							}
+
+						});
                 }
 
                 // Array?