简体   繁体   English

有没有一种方法可以使用json.net序列化嵌入的对象

[英]Is there a way to serialize embeded objects using json.net

I am trying to simulate a foreign key behaviour using JSON.Net but I can't seem to find a way to have the real references. 我正在尝试使用JSON.Net模拟外键行为,但是我似乎找不到找到真正引用的方法。

Let's say I have this simple example: 假设我有一个简单的例子:

private static void Main(string[] args)
        {
            var g1 = new Group {Name = "g1"};
            var g2 = new Group {Name = "g2"};

            var users = new[]
            {
                new User{ Username = "truc", Group = g1 },
                new User{ Username = "machin", Group = g2 },
                new User{ Username = "dom", Group = g2 },
                new User{ Username = "boum", Group = g2 }
            };

            string json = JsonConvert.SerializeObject(users);

            var jsonUsers = JsonConvert.DeserializeObject<User[]>(json);

            Console.WriteLine(jsonUsers[2].Group == jsonUsers[3].Group);

            Console.ReadLine();
        }

the problem here is that Console.WriteLine(jsonUsers[2].Group == jsonUsers[3].Group); 这里的问题是Console.WriteLine(jsonUsers[2].Group == jsonUsers[3].Group); is always false. 永远是错误的。

The only way I found that would make it work would be to store a list of users, then a list of group and having a GroupId proprety Inside of users. 我发现使之起作用的唯一方法是存储一个用户列表,然后存储一个组列表,并在用户内部拥有一个GroupId属性。 Then after everything is deserialized, I manually insert references of groups Inside of users. 然后,在对所有内容进行反序列化之后,我手动在用户内部插入组的引用。 It's hackish. 有点黑

What would be the best way to approach this problem ? 解决这个问题的最佳方法是什么?

You are making the instance-comparison. 您正在进行实例比较。 you should override Equals and GetHashcode in Group class. 您应该在Group类中重写EqualsGetHashcode Operator overloading would also be good since you use == operator in Console.WriteLine 由于您在Console.WriteLine中使用==运算符,因此运算符重载也很好。

Otherwise; 除此以外;

new Group() { Name = "a" } == new Group() { Name = "a" }

or 要么

new Group() { Name = "a" }.Equals(new Group() { Name = "a" })

would always return false 总是会返回false

.

public class Group
{
    public string Name;
    public int i;


    public static bool operator ==(Group a, Group b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(Group a, Group b)
    {
        return !(a.Name == b.Name);
    }

    public override bool Equals(object obj)
    {
        var g = obj as Group;
        if (ReferenceEquals(this,g)) return true;
        return g.Name.Equals(Name);
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM