Return only filled fields in the web service

0

I made a REST with WCF. In a method it returns me an object. It turns out that I do not fill in all the fields of this object and it shows all in the response xml. How do I display only the fields that have value, ie the ones that I fill in?

    
asked by anonymous 27.05.2014 / 20:27

1 answer

2

To prevent object fields from being serialized in XML (or JSON), you can use the EmitDefaultValue property of the [DataMember] attribute. If it has the value false , numbers with value 0 , bool with value false or objects with value null will not be included in the answer.

public class PT_StackOverflow_17297
{
    [DataContract(Name = "MinhaClasse", Namespace = "")]
    public class MinhaClasse
    {
        [DataMember(EmitDefaultValue = false)]
        public string Nome { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public int Valor { get; set; }

        [DataMember(EmitDefaultValue = false)]
        public bool Flag { get; set; }
    }
    [ServiceContract]
    public class Service
    {
        [WebGet(ResponseFormat = WebMessageFormat.Xml)]
        public MinhaClasse Get()
        {
            var rndGen = new Random();
            var result = new MinhaClasse();
            result.Nome = rndGen.Next(2) == 0 ? "Alguma coisa" : null;
            result.Valor = rndGen.Next(2) == 0 ? 123 : 0;
            result.Flag = rndGen.Next(2) == 0;
            return result;
        }
    }
    public static void Test()
    {
        var baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        var host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
        host.Open();
        Console.WriteLine("Host opened");

        var c = new WebClient();
        for (var i = 0; i < 5; i++)
        {
            Console.WriteLine(c.DownloadString(baseAddress + "/Get"));
            Thread.Sleep(50);
        }

        Console.ReadLine();
        host.Close();
    }
}
    
11.06.2014 / 20:05