Merging objects

11/16/2018 18:29 ssamko#1
Hello guys I want to merge 2 objects to 1. Those objects can have properties which can have properties etc(multilevel). An in case the source object has some null properties they wont replace old data.
Why do I need it ? I got some JSON data from game and I put them to object with specified structure.

Struct of my object:
Code:
public partial class JsonObjects
{
        [JsonProperty("data")]
        public Data Data { get; set; }
}

public partial class Data
{
        [JsonProperty("user")]
        public User User { get; set; }

        [JsonProperty("character")]
        public Character Character { get; set; }
}
	
public partial class User
{
        [JsonProperty("id")]
        public long? Id { get; set; }

        [JsonProperty("email")]
        public string Email { get; set; }
}
	
public partial class Character
{
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("game_currency")]
        public long? GameCurrency { get; set; }
}
Main:
Code:
JsonObjects destination = new JsonObjects();
string html;
while(true){
	html= GetFreshData();
	JsonObjects newData = JsonConvert.DeserializeObject<JsonObjects>(html);
	// put NEW data from obj: "newData" to "destination"
}
Do you have an idea how can I effectively merge it ?

Thank you !
11/19/2018 16:53 Hypos'#2
I don't know if I got you right there but what you're seemingly looking for is a "deep merge" function.

Basically you loop through your new object and see if it has any property that is _not_ already in the source object (on the same level, I suppose?). If the respective source property is a null-reference you just ignore it and continue the loop.

If the property is an object itself, you call the function recursively.

Of course this solution requires a JSON parser, but you can find plenty of those on the net and NuGet.
11/21/2018 20:42 ssamko#3
Quote:
Originally Posted by Hypos' View Post
I don't know if I got you right there but what you're seemingly looking for is a "deep merge" function.

Basically you loop through your new object and see if it has any property that is _not_ already in the source object (on the same level, I suppose?). If the respective source property is a null-reference you just ignore it and continue the loop.

If the property is an object itself, you call the function recursively.

Of course this solution requires a JSON parser, but you can find plenty of those on the net and NuGet.
yes you did understand it well..so called "deep merge" is what I wanted and finally I have found one library for that on Nuget. Thnx !