Json 和循环引用异常 [英] Json and Circular Reference Exception

查看:28
本文介绍了Json 和循环引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它具有对另一个对象的循环引用.鉴于这些对象之间的关系,这是正确的设计.

I have an object which has a circular reference to another object. Given the relationship between these objects this is the right design.

说明

Machine => Customer => Machine

不出所料,当我尝试使用 Json 序列化机器或客户对象时遇到了问题.我不确定如何解决这个问题,因为我不想破坏 Machine 和 Customer 对象之间的关系.解决此问题的选项有哪些?

As is expected I run into an issue when I try to use Json to serialize a machine or customer object. What I am unsure of is how to resolve this issue as I don't want to break the relationship between the Machine and Customer objects. What are the options for resolving this issue?

编辑

目前我正在使用 提供的 Json 方法控制器基类.所以我正在做的序列化很基本:

Presently I am using Json method provided by the Controller base class. So the serialization I am doing is as basic as:

Json(machineForm);

推荐答案

更新:

不要尝试使用 NonSerializedAttribute,因为 JavaScriptSerializer 显然会忽略它.

Do not try to use NonSerializedAttribute, as the JavaScriptSerializer apparently ignores it.

改为使用 System.Web.Script.Serialization 中的 ScriptIgnoreAttribute.

public class Machine
{
    public string Customer { get; set; }

    // Other members
    // ...
}

public class Customer
{
    [ScriptIgnore]
    public Machine Machine { get; set; }    // Parent reference?

    // Other members
    // ...
}

这样,当你把一个Machine扔进Json方法时,它会遍历从MachineCustomer<的关系/code> 但不会尝试从 Customer 返回到 Machine.

This way, when you toss a Machine into the Json method, it will traverse the relationship from Machine to Customer but will not try to go back from Customer to Machine.

关系仍然存在,您的代码可以随心所欲,但 JavaScriptSerializer(由 Json 方法使用)将忽略它.

The relationship is still there for your code to do as it pleases with, but the JavaScriptSerializer (used by the Json method) will ignore it.

这篇关于Json 和循环引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆