How to serialzie System.Enum with Newtonsoft.Json?

  Kiến thức lập trình

I have the following enum

public enum SomeEnum
{ 
    One,Two, Three
}

And the following code throws exception

 Dictionary<Enum, string> map = new Dictionary<Enum, string>()
 { {SomeEnum.One,"1"},{SomeEnum.Two,"2"},{SomeEnum.Three,"3"}   };

 string mapStr = JsonConvert.SerializeObject(map, Formatting.None,new JsonSerializerSettings() { TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full});

 var newMap = JsonConvert.DeserializeObject<Dictionary<Enum, string>>(mapStr);
Newtonsoft.Json.JsonSerializationException: 'Could not convert string 'One' to dictionary key type 'System.Enum'. Create a TypeConverter to convert from the string to the key type object. Path 'One', line 1, position 7.'

Probably because the serialized Json does not contain any type definition that hints about the original run time enum type, and seems like using TypeNameAssemblyFormatHandling doesn’t help either.

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

How to serialzie System.Enum with Newtonsoft.Json?

I have the following enum

public enum SomeEnum
{ 
    One,Two, Three
}

And the following code throws exception

 Dictionary<Enum, string> map = new Dictionary<Enum, string>()
 { {SomeEnum.One,"1"},{SomeEnum.Two,"2"},{SomeEnum.Three,"3"}   };

 string mapStr = JsonConvert.SerializeObject(map, Formatting.None,new JsonSerializerSettings() { TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full});

 var newMap = JsonConvert.DeserializeObject<Dictionary<Enum, string>>(mapStr);
Newtonsoft.Json.JsonSerializationException: 'Could not convert string 'One' to dictionary key type 'System.Enum'. Create a TypeConverter to convert from the string to the key type object. Path 'One', line 1, position 7.'

Probably because the serialized Json does not contain any type definition that hints about the original run time enum type, and seems like using TypeNameAssemblyFormatHandling doesn’t help either.

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT