有人可以建议一种更新 Cheese.Producers 列表中项目的方法吗?
我有以下类(class):
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>();
}
}
在主要代码中,我有一个对象 (gouda),我想根据从文件中读取的 JSON 来更新它。
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);
}
JSON 更新文件:
{
"Name": "Hard Blue",
"Taste": "Sharp",
"Producers": [
{
"Name": "prod1",
"Rating": 100
},
{
"Name": "prod3",
"Rating": 300
}
]
}
主要问题是当调用 PopulateObject 时,没有更新 Producers 列表项,而是添加了 2 个新成员。其他领域似乎工作得很好。 有什么建议吗?
最佳答案
试试这个:
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);
var propertiesToBeAdded = File.ReadAllText(@"C:\json path");
var settings = new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Merge
};
var o1 = JObject.Parse(JsonConvert.SerializeObject(gouda));
o1.Merge(JObject.Parse(propertiesToBeAdded), settings);
var o = o1.ToString();
您需要稍微更改一下 JSON
格式:
{
'Name': 'Hard Blue',
'Taste': 'Sharp',
'Producers': [
{
'Name': 'prod1',
'Rating': 100
},
{
},
{
'Name': 'prod3',
'Rating': 300
}
]
}
开始吧:
希望这对您有所帮助。
关于c# - JSON.NET - 使用列表更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403007/