Tar
Tar

Reputation: 9015

How to receive Json with spaced fields-names in asp.net web-api?

In my MVC-4 Web-API server, I receive a Json string that contains spaces in it's names:

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

I defined a Model class, e.g:

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

    public string SimpleName { get; set; }
}

Now SimpleName passes through (in spite it's first letter capitalization mismatch, which is good), but FieldName becomes null.

How can I successfully receive Json that has spaces in it's fields' names (predefined - I cannot change the client data source) ?

Upvotes: 0

Views: 1023

Answers (1)

Maggie Ying
Maggie Ying

Reputation: 10175

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."

Upvotes: 2

Related Questions