【问题标题】:WCF Restful service parse enum within json cause errorWCF Restful服务解析json中的枚举导致错误
【发布时间】:2012-06-14 04:27:06
【问题描述】:

我有一个基于 WCF 的宁静服务,如下所示: (FeedbackInfo 类只有一个 enum 成员 - ServiceCode。)

[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public List<FeedbackInfo> GetFeedbackInfoList(ServiceCode code)
{
    return ALLDAO.GetFeedbackInfoList(code);
}

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public int? CreateFeedback(FeedbackInfo feedback)
{
    return ALLDAO.CreateFeedback(feedback);
}

我将使用 jquery ajax 来调用这两个方法,如下所示:

$.ajax({
    type: "GET",
    url: "/Service/ALL.svc/GetFeedbackInfoList",
    datatype: "text/json",
    data: { "code": "Info"},
});



var feedbackInfo = { feedback: {
    ServiceCode: "Info"
}};
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/Service/ALL.svc/CreateFeedback",
    datatype: "text/json",
    data: JSON.stringify(feedbackInfo),
});

第一次调用将成功执行,而第二次调用给我一个错误:值“Info”无法解析为类型“Int64”。我想知道为什么在第二次调用中不能解析同一个枚举?仅仅因为枚举类型被用作类的成员?

编辑: FeedbackInfo 和 ServiceCode 如下所示:

public class FeedbackInfo
{
    public int ID { get; set; }
    public string Title { get; set; }
    public ServiceCode ServiceCode { get; set; }
}
[DataContract]
public enum ServiceCode
{
    [EnumMember]
    Info,
    [EnumMember]
    Error
}

【问题讨论】:

标签: wcf wcf-rest


【解决方案1】:

枚举被序列化为整数,因此您需要使用 ServiceCode: 1(或其他),或者,在 FeedbackInfo 类中添加自定义属性以从给定字符串反序列化枚举价值。即,像这样:

public string ServiceCode { 
    get {
        return ServiceCodeEnum.ToString();
    }
    set {
        MyEnum enumVal;
        if (Enum.TryParse<MyEnum>(value, out enumVal))
            ServiceCodeEnum = enumVal;
        else
            ServiceCodeEnum = default(MyEnum);
    }
}

private MyEnum ServiceCodeEnum { get; set; }

【讨论】:

  • 然而,在第一次调用中,wcf 将字符串从 jquery 解析为 enum 成功。
  • @Domi.Zhang 啊,我明白你的意思了。对不起。
  • 感谢您的帮助。
【解决方案2】:

我已经组合了一个使用Newtonsoft.Json 库的更好的解决方案。它修复了枚举问题,也使错误处理变得更好。代码挺多的,可以在 GitHub 上找到:https://github.com/jongrant/wcfjsonserializer/blob/master/NewtonsoftJsonFormatter.cs

您必须在Web.config 中添加一些条目才能使其正常工作,您可以在此处查看示例文件: https://github.com/jongrant/wcfjsonserializer/blob/master/Web.config

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多