Could someone suggest a method of updating the items in the Cheese.Producers list?
I have the following classes:
class Producer
{
public string Name { get; set; }
public int Rating { get; set; }
public Producer()
{
}
public Producer(string name, int rating)
{
Name = name;
Rating = rating;
}
}
class Cheese
{
public string Name { get; set; }
public int Age { get; set; }
public string Taste { get; set; }
public List<Producer> Producers { get; set; }
public Cheese()
{
Producers = new List<Producer>();
}
public Cheese(string name, int age)
{
Name = name;
Age = age;
Producers = new List<Producer>();
}
public Cheese(string name, int age, string taste)
{
Name = name;
Age = age;
Taste = taste;
Producers = new List<Producer>();
}
}
In the main code I have an object(gouda) that I want to update based on a JSON read from a file.
static void Main(string[] args)
{
Producer prod1 = new Producer("prod1", 5);
Producer prod2 = new Producer("prod2", 6);
Producer prod3 = new Producer("prod3", 7);
Cheese gouda = new Cheese("Gouda", 5, "Mild");
gouda.Producers.Add(prod1);
gouda.Producers.Add(prod2);
gouda.Producers.Add(prod3);
string propertiesToBeAdded = File.ReadAllText("properties.txt");
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Reuse
};
JsonConvert.PopulateObject(propertiesToBeAdded, gouda, jsonSerializerSettings);
}
The JSON update file:
{
"Name": "Hard Blue",
"Taste": "Sharp",
"Producers": [
{
"Name": "prod1",
"Rating": 100
},
{
"Name": "prod3",
"Rating": 300
}
]
}
The major problem is that when the PopulateObject is called, instead of updating the Producers list items, 2 new members are added. The other fields seem to work just fine. Any suggestions?

ObjectCreationHandling.Replace? see stackoverflow.com/questions/31025153/…Cheese partialCheese = JsonConvert.DeserializeObject<Cheese>(propertiesToBeAdded)isn't populating desired result I guess.{ "Name": "Hard Blue", "Age": 5, "Taste": "Sharp", "Producers": [ { "Name": "prod1", "Rating": 100 }, { "Name": "prod2", "Rating": 6 }, { "Name": "prod3", "Rating": 300 } ] }