简体   繁体   中英

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.

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); 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. 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. Operator overloading would also be good since you use == operator in 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

.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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