gpt4 book ai didi

c# - 处理 JSON.net 中的引用循环

转载 作者:太空狗 更新时间:2023-10-29 23:31:20 26 4
gpt4 key购买 nike

我希望将项目集合 ( List<Item>) 序列化为 JSON。

这些项目的集合为 Connection它提供有关来自一个 Item 的连接的信息一秒Item .由于连接对象具有对项目的引用,因此它使其成为一个无限循环。

我的问题是有没有办法在第二次序列化对象时跳过连接集合的序列化。

我试过从 JsonConverter 继承之类的东西并编写自定义 WriteJson()方法,但从那里我不知道是否应该写出数组。

我也尝试过使用自定义 ContractResolver,但效果不佳。


public class Item
{
private static int _lastID = 0;

public Item()
{
ID = ++_lastID;
Connections = new List<Connection>();
}


public int ID { get; set; }

public string Name { get; set; }

public string Prop1 { get; set; }

public string Prop2 { get; set; }

public List<Connection> Connections { get; set; }

}



public class Connection
{
private Connection(ConnectionType type, Item source, Item target)
{
if (type == ConnectionType.None)
throw new ArgumentException();
if (source == null)
throw new ArgumentNullException("source");
if (target == null)
throw new ArgumentNullException("target");

Type = type;
Source = source;
Target = target;
}


public ConnectionType Type { get; set; }

public Item Source { get; set; }

public Item Target { get; set; }


public static void Connect(ConnectionType type, Item source, Item target)
{
var conn = new Connection(type, source, target);
source.Connections.Add(conn);
target.Connections.Add(conn);
}
}


想要的结果:

[
{
"id": 1,
"name": "Item #1",
"prop1": "val1",
"prop2": "val2",
"connections": {
"type": "ConnType",
"source": {
"id": 1,
"name": "Item #1",
"prop1": "val1",
"prop2": "val2"
// no connections array
},
"target": {
"id": 2,
"name": "Item #2",
"prop1": "val1",
"prop2": "val2"
// no connections array
}
}
},
{
"id": 2,
"name": "Item #2",
"prop1": "val1",
"prop2": "val2",
"connections": {
"type": "ConnType",
"source": {
"id": 1,
"name": "Item #1",
"prop1": "val1",
"prop2": "val2"
// no connections array
},
"target": {
"id": 2,
"name": "Item #2",
"prop1": "val1",
"prop2": "val2"
// no connections array
}
}
}
]



编辑:

C#

var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
};
settings.Converters.Add(new StringEnumConverter());
var json = JsonConvert.SerializeObject(collection, settings);

最佳答案

将其添加到您的 Global.asax(或在 WebApiConfig 或任何其他配置类中)

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

关于c# - 处理 JSON.net 中的引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22297173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com