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

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

问题描述

我有具有圆形参照其他对象的对象。鉴于这些对象之间的关系,这是正确的设计。

为了说明

 机=>客户= GT;机

由于预计我遇到一个问题,当我尝试使用JSON序列化机或客户对象。什么我不确定的是如何解决这个问题,因为我不想打破机器和客户对象之间的关系。什么是解决这一问题的选项?

修改

presently我使用的控制器提供 Json的方法基类。所以,我做的序列化是基本的:

  JSON(machineForm);


解决方案

更新:

不要试图用 NonSerializedAttribute ,因为的JavaScriptSerializer 显然忽略它。

相反, System.Web.Script.Serialization 使用 ScriptIgnoreAttribute

 公共类机
{
    公共字符串的客户{搞定;组; }    //其他成员
    // ...
}公共类客户
{
    [ScriptIgnore]
    公共机机器{搞定;组; } //家长参考?    //其他成员
    // ...
}

这样,当你折腾一个的Json 方法,它会遍历从<关系code>机到客户,但不会尝试从客户回去

的关系仍然存在于你的code ++做的,因为它与喜悦,但的JavaScriptSerializer (由的Json 法)将其忽略。

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

To Illustrate

Machine => Customer => Machine

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?

Edit

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

Json(machineForm);

解决方案

Update:

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

Instead, use the ScriptIgnoreAttribute in System.Web.Script.Serialization.

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

    // Other members
    // ...
}

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

    // Other members
    // ...
}

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.

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天全站免登陆