Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure WebMethods to use DataContractJsonSerializer

It appears that ASP.NET web methods use the JavaScriptSerializer, as it ignores my [DataContract] and [DataMember] attributes on my objects.

I have an object that looks like this:

[DataContract]
public class MyObject
{
    [DataMember("firstField")]
    public string FirstField { get; set; }
    [DataMember("secondField")]
    public string SecondField { get; set; }
}

My web method looks like this:

[WebMethod]
public static IEnumerable<MyObject> GetData() { ... }

Among other things, I want the JSON property names to come out as firstField rather than FirstField.

Is there a way to configure WebMethods to use DataContractJsonSerializer so that it respects the DataMember annotations?

like image 600
Matthew Rodatus Avatar asked Jan 17 '26 01:01

Matthew Rodatus


1 Answers

[WebMethod] and any of the Data Contract serializers are totally unrelated pieces of technology, and they cannot be mixed. If you want to use DataContractJsonSerializer, then you need to use WCF, not the old ASMX technology used by [WebMethod].

like image 180
John Saunders Avatar answered Jan 19 '26 15:01

John Saunders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!