What exactly happens in .net when a webservice call parses a JSON object?
Suppose I write the following C# code to define a web method:
public class Thing
{
public string X {get;set}
public string Y {get;set}
}
[WebMethod]
public static void myFunction(Thing thing) { }
I've discovered that I can invoke the function using the jQuery JavaScript that looks like this:
var myData = { X: "hello", Y: "world" };
var jsonData = JSON.stringify(myData);
jQuery.ajax({ data: jsonData, ...
When myFunction
is thus invoked, thing.X
is set to "hello" and thing.Y
is set to "world". What exactly does the .net framework do to set the value of thing
开发者_C百科? Does it invoke a constructor?
Just like you can create Thing like so
Thing x = new Thing { X = "hello", Y = "world" }
So no it does not call the constructor to answer your question.
Ok, more detail...
It takes the JSON and deserializes it. It fills the properties from you JSON object. For example, if you had the following in JSON:
{"notRelated":0, "test": "string"}
The serializer would not find X or Y for thing and set them to the default value for that data type.
Let's say you want to go deeper. You can custom serialize and deserialize your objects:
[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;
public MyObject()
{
}
protected MyObject(SerializationInfo info, StreamingContext context)
{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}
So you can see, it's fishing for parameters in your case, X
and Y
.
精彩评论