Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

c# - parsing an enumeration in JSON.net

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...