Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp web api json serialization returns private properties

I have a Web api controller class and i call a method on a proxy class generated from a WSDL from the web api controller, and i return an object of type defined in the WSDL proxy class.

but the xml/json returned contains the private members of the proxy class

the private members are

    private string companyField;

    private string soldBPField;

    private string fromDateField;

    private string toDateField;

    private long succStatusField;

and the xml returned is :

<companyField>700</companyField>
<soldBPField>999000353</soldBPField>
<fromDateField>01-01-2012</fromDateField>
<toDateField>01-01-2013</toDateField>

the json returned is also similar

I changed the xml formatter in the global.asax as follows:

var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

this changed the XML returned to:

<company>700</company>
<soldBP>999000353</soldBP>
<fromDateField>01-01-2012</fromDate>
<toDate>01-01-2013</toDate>

but the json returned still contains the name of the private variables

can any one help me with this

like image 428
Anoopsingh Bayes Avatar asked Jun 27 '13 10:06

Anoopsingh Bayes


People also ask

How can we hide a property in Web API?

To ignore individual properties, you can use the [JsonIgnore] attribute,like this: Model: public class Emp.

What is the standard serialization format used by ASP Web APIs?

JSON and XML Serialization in ASP.NET Web API.

Can ASP net Web API specialize to XML or JSON?

Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.


1 Answers

Are your types marked as [Serializable]? Serializable means that the serializer should serialize all fields - private or public. Try to remove Serializable or else use this line to stop the JSON formatter from recognizing the attribute:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
like image 155
Youssef Moussaoui Avatar answered Oct 21 '22 18:10

Youssef Moussaoui