解析 JSON.net 中的枚举 [英] parsing an enumeration in JSON.net

查看:27
本文介绍了解析 JSON.net 中的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSON.net(也许是 v3.5ish?它是 2010 年 10 月的).我正在尝试将一些 json 反序列化为一个枚举:

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

几何类型:esriGeometryPolygon"

geometryType: "esriGeometryPolygon"

我有这个枚举:

/// <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
}

但它会抛出一个错误,提示将值esriGeometryPolygon"转换为...GeometryType"时出错.

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

我在这里遗漏了什么?

是不是因为它是旧版本(我使用的是单点触控端口:https://github.com/chrisntr/Newtonsoft.Json 一年没更新了)?还是我的数据合同弄错了?

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?

我将最新的 JSON.NET 移植到 MT,但我仍然遇到完全相同的错误.

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

推荐答案

根据 JSON.NET 文档,默认行为是对枚举使用 int 值:http://james.newtonking.com/projects/json/help/SerializationGuide.html

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

您可以通过在枚举上添加带有 StringEnumConverter 的 JsonConverter 属性来更改它...

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

文档:使用 JsonConverters 进行序列化

这篇关于解析 JSON.net 中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆