问题
I have several BusinessObject classes that refer to each other and I need to serialize one in a JsonResponse and return it to my view. I keep getting a circular reference exception and I cannot get rid of it. I have placed the [ScriptIgnore()]
decorator on every property that is not a simple data type property and I am still getting the exception. I cant figure out where the problem is, as I am blocking the serializer from just about everything and it is still blowing up on me.
Is there any way to see what they current state of the serialized object is?
[HttpPost]
public JsonResult GetAnalysisInfo(int id)
{
ProjectContext myDB = db;
SearchAnalysis searchanalysis = SearchAnalysis.Find(myDB, id);
//searchanalysis.Results = searchanalysis.SearchResultsPrototype(myDB);
return this.Json(searchanalysis);
}
Update
I have also tried implementing ISerializable to no avail. My GetObjectData is very simple:
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("SearchAnalysisId", this.SearchAnalysisId);
info.AddValue("Created", this.Created);
}
Still getting a CircularRefernce error. DateTime data types don't cause problems with Serialization right?
回答1:
What I'm doing to prevent that error is to return an anonymouse type that reflects my object's properties like this :
public JsonResult CompanyListJson()
{
var list = (from companies in appContext.Companies
where companies.Active.Equals(true)
select new
{
Name = companies.DbName,
Id = companies.Id,
Active = companies.Id.Equals(CurrentCompany.Id)
});
return Json(list, JsonRequestBehavior.AllowGet);
}
Maybe it's not the best way, but it allows me to keep my JSON thin and push only the data I need ( and avoid that circular reference exception of course )
Looking at your sample, I would select new anonymouse type from SearchAnalysis, taking the properties I need. That should work
来源:https://stackoverflow.com/questions/9263987/circular-references-and-scriptignore-problems