技术开发 频道

自定义JavaScriptConverter处理循环引用对象


【IT168技术文档】

1 public class Boy 2 { 3 public string Name; 4 5 public Girl Girlfriend; 6 } 7 8 public class Girl 9 { 10 public string Name; 11 12 public Boy Boyfriend; 13 }
  解决服务器端序列化问题:

  我们先写需要使用的Web Services方法:
1 [WebService(Namespace = "http://tempuri.org/")] 2 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 3 public class BoyAndGirl : System.Web.Services.WebService { 4 5 [WebMethod] 6 public Boy GetBoyWithGirlfriend(string boyName, string girlName) 7 { 8 Boy boy = new Boy(); 9 boy.Name = boyName; 10 11 Girl girl = new Girl(); 12 girl.Name = girlName; 13 14 boy.Girlfriend = girl; 15 girl.Boyfriend = boy; 16 17 return boy; 18 } 19 }
  很显然,它们存在循环引用,如果使用了 Atlas内部的JSON序列化方法的话,就会抛出异常。那么我们该怎么解决这个问题呢?方法就是自定义一个JavaScriptConvert。在这里,我们写一个BoyConverter,首先重载它的SupportedTypes属性,表明这个Converter所支持的类型。
1 public class BoyConverter : JavaScriptConverter 2 { 3 protected override Type[] SupportedTypes 4 { 5 get 6 { 7 return new Type[] { typeof(Boy) }; 8 } 9 } 10 }
0
相关文章