当webservice调用解析JSON对象时,在.net中究竟发生了什么?

What exactly happens in .net when a webservice call parses a JSON object?

本文关键字:net 究竟 发生了 什么 调用 webservice 对象 JSON      更新时间:2023-09-26

假设我编写以下c#代码来定义一个web方法:

public class Thing
{
    public string X {get;set}
    public string Y {get;set}
}
[WebMethod]
public static void myFunction(Thing thing) { }

我发现我可以使用jQuery JavaScript调用函数,看起来像这样:

var myData = { X: "hello", Y: "world" };
var jsonData = JSON.stringify(myData);
jQuery.ajax({ data: jsonData, ...

当调用myFunction时,thing.X设置为"hello",thing.Y设置为"world"。究竟是什么。net框架做设置thing的值?它调用构造函数吗?

就像你可以创建这样的东西

Thing x = new Thing { X = "hello", Y = "world" }

所以它不会调用构造函数来回答你的问题。

好的,更多细节…

它接受JSON并对其进行反序列化。它填充JSON对象的属性。例如,如果在JSON中有以下内容:

{"notRelated":0, "test": "string"}

序列化器不会为thing找到X或Y,并将它们设置为该数据类型的默认值。

假设你想更深入。您可以自定义序列化和反序列化您的对象:

[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);
  }
}

你可以看到,它正在寻找参数在你的例子中,XY