0

在我的 MVC-4 Web-API 服务器中,我收到一个名称中包含空格的 Json 字符串:

{ "field name" : "some value" , "simpleName" : "some string" }

我定义了一个Model类,例如:

public class SomeJsonModel
{
    [DataMember(Name = "field name")]
    public string FieldName { get; set; }

    public string SimpleName { get; set; }
}

现在SimpleName通过(尽管它的第一个字母大写不匹配,这很好),但FieldName变成null.

如何成功接收字段名称中有空格的 Json(预定义 - 我无法更改客户端数据源)?

4

1 回答 1

2

Try adding [DataContract] on your class:

[DataContract]
public class SomeJsonModel
{
    [DataMember(Name = "field name")]
    public string FieldName { get; set; }

    [DataMember]
    public string SimpleName { get; set; }
}

Here is more info about this:

  • on MSDN: "Apply the DataMemberAttribute attribute in conjunction with the DataContractAttribute to identify members of a type that are part of a data contract."
  • a Json.NET issue relating to the DataMember's Name property being ignored. The resolution for that was to "Put DataContract on the class."
于 2012-10-18T16:20:47.893 回答