Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...