序列化“System.Web.HttpContext”类型的对象时检测到循环引用

时间:2016-02-08 09:25:42

标签: asp.net

我想以这种格式{"Part_ID":"2","Part_NAME":"\u0645\u0633\u062a\u0644\u0632\u0645\u0627 "}

从asp.net Web服务返回一个json对象

但是我收到以下错误

  

System.InvalidOperationException:检测到循环引用   在序列化'System.Web.HttpContext'类型的对象时。

代码是:

      public class Service : System.Web.Services.WebService
      {
        public string name;  
        public Service()
        {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
        }

        [WebMethod(Description = "Your Description")]
        public string FunctionName()
        {
          var a = new Service { name = "tamzinho" };
          JavaScriptSerializer js = new JavaScriptSerializer();
          string retJSON = js.Serialize(a);
          return retJSON;
        }
      }

1 个答案:

答案 0 :(得分:0)

var a = new Service { name = "tamzinho" };
...
string retJSON = js.Serialize(a);

此代码是您的问题:序列化将无限尝试,因为您尝试序列化同一个类的实例,这将尝试序列化另一个实例(依此类推......)

将您的数据分成单独的对象。

例如:

public class MyServiceData {
   public string Name { get; set; }
   public string Description { get; set; }
}

public class Service : System.Web.Services.WebService
{
   public MyServiceData GetInfo(int partId) {
       ... data access code
       var result = new MyServiceData() { 
           Name = ...;
           Description = ...;
       };

      ... serialize result data to javascript
      return result;
   }
}