none
How to return not null filed in wcf json RRS feed

Answers

  • Hi,

    WCF uses the DataContractJsonSerializer for serializing objects to JSON. And the DataMember attributes have an EmitDefaultValue property (default is true; see docs here):

    I create the following code and it work well in my computer:
    Iservice:
    namespace WcfService3
    {    
    [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "data/{id}")] Person GetData(string id); } [DataContract] public class Person { [DataMember] public int id { get; set; } [DataMember (EmitDefaultValue=false)] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } } }

    Service:

     public class Service1 : IService1
        {
            public Person GetData(string id)
            {
                return new Person()
                {
                    id = Convert.ToInt32(id),
                    FirstName = null,
                    LastName="sds"
                };
            }
    
            }
    
           
    }

    Then if I put the id="123", then it will return:

    {"LastName":"sds","id":123}

    Best Regards.


    Amy Peng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    • Marked as answer by Professo Monday, August 12, 2013 8:05 AM
    Tuesday, August 6, 2013 7:03 AM
    Moderator