【问题标题】:Can MVC deserialize the json string which is having perl_script naming conventionMVC 可以反序列化具有 perl_script 命名约定的 json 字符串吗
【发布时间】:2016-08-26 21:26:32
【问题描述】:

我们正在与将以下对象作为表单发布的一部分传递的第三方供应商合作

{
    "application": 123,
    "order_reference": "01234",
    "new_status": "initialize"
}

由于这不是 C# 中的标准命名约定,我创建了以下模型。

public class Response
{
    [JsonProperty("application")]
    public string Application {get; set;}

    [JsonProperty("order_reference")]
    public string OrderReference {get; set;}

    [JsonProperty("new_status")]
    public string NewStatus {get; set;}
}

我在控制器中有以下代码。

[HttpPost]
public Notify(Response response)
{
   // code.
}

请求来自上述方法,但对象没有反序列化,我可以看到,只有 application 属性被映射。

谁能告诉我,我是否可以使它与我创建的模型一起工作,还是我必须创建与响应相同的模型?

【问题讨论】:

  • 您是否已将应用配置为使用 JSON.Net 作为默认 JavaScript 序列化程序?
  • @StephenMuecke:不,我没有。不知道该怎么做。而且我不想将其设为所有 Action 方法的默认值。
  • 您可以在 C# 中将此约定用于属性名称。只需将 JASON.Stringify 用于 ajax 请求中的数据。
  • @AftabAhmed:你能详细说明一下吗?
  • 看看this question/answer。如果您不想将其用作默认值,那么我认为您需要将参数设为字符串并使用Json.Net 对其进行反序列化。

标签: c# json asp.net-mvc asp.net-mvc-3


【解决方案1】:

只需将您的属性包装在一个 json 对象中并对其进行字符串化。我已经测试过了,它正在工作

   var Response = {
                response:{

                    'Application': "123",
                    'order_reference': "01234",
                    'new_status': "initialize"

                }
            };

接收 Ajax 请求的 C# 代码

    [HttpPost]
    public Notify(Response response)
    {
        // code.
    }

    public class Response
    {
        public string Application { get; set; }

        public string order_reference { get; set; }

        public string new_status { get; set; }
    }

【讨论】:

  • 这可行,但这不是 C# 中的标准命名约定。有什么替代方法吗?
  • 您可以使用任何命名约定,只需包装您的对象并将其字符串化。
猜你喜欢
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多