parsing an enumeration in JSON.net

10,563

According to JSON.NET documentation, default behavior is to use int value for Enums : http://james.newtonking.com/projects/json/help/SerializationGuide.html

You can change that by adding a JsonConverter attribute with StringEnumConverter on your enum...

/// <summary>
/// The geometry type.
/// </summary>
[DataContract]
[JsonConverter(typeof(StringEnumConverter))]
public enum GeometryType

Documentation: Serialize with JsonConverters

Share:
10,563
bryan costanich
Author by

bryan costanich

Updated on June 06, 2022

Comments

  • bryan costanich
    bryan costanich about 2 years

    i'm using JSON.net (maybe v3.5ish? it's from oct. 2010). and i'm trying to deserialize some json into an enumeration:

    geometryType: "esriGeometryPolygon"

    i have this enumeration:

    /// <summary>
    /// The geometry type.
    /// </summary>
    [DataContract]
    public enum GeometryType
    {
        /// <summary>
        /// Refers to geometry type Envelope
        /// </summary>
        [EnumMember(Value = "esriGeometryEnvelope")]
        Envelope,
        /// <summary>
        /// Refers to geometry type MultiPoint
        /// </summary>
        [EnumMember(Value = "esriGeometryMultipoint")]
        MultiPoint,
        /// <summary>
        /// Refers to geometry type MapPoint
        /// </summary>
        [EnumMember(Value = "esriGeometryPoint")]
        Point,
        /// <summary>
        /// Refers to geometry type Polygon
        /// </summary>
        [EnumMember(Value = "esriGeometryPolygon")]
        Polygon,
        /// <summary>
        /// Refers to geometry type Polyline
        /// </summary>
        [EnumMember(Value = "esriGeometryPolyline")]
        Polyline
    }
    

    but it throws an error saying "Error converting value "esriGeometryPolygon" to type '...GeometryType'.

    what am i missing here?

    is it because it's an old version (i'm using the monotouch port: https://github.com/chrisntr/Newtonsoft.Json which hasn't been updated in a year)? or did i get my datacontract wrong?


    EDIT: i ported the latest JSON.NET to MT and i'm still getting the exact same error.

  • Mose
    Mose about 10 years
    Alternatively, if you want to avoid coupling between DTO an Json.Net, you can add the converter at serializer level : var serializer = new JsonSerializer(); serializer.Converters.Add(new StringEnumConverter());