在“分期付款”中反序列化Json

时间:2017-08-29 17:57:31

标签: c# json deserialization

所以,假设我有一个模型,我想填充数据,但不是一次填充所有数据。

模型是:

public class SubPlayground
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("weekdays")]
    public List<Dictionary<string, string>> Weekdays { get; set; }
}

//Say here we want to populate the first two properties
var m = JsonConvert.DeserializeObject<SubPlayground>(jsonString1);

//And here populate the third one without overriding the first two
m = JsonConvert.DeserializeObject<SubPlayground>(jsonString2);

有解决方法吗?

编辑: 为了澄清:两个jsonString不同,每个都只包含相应的属性。因此jsonString1将包含名称和类型,而jsonString2将仅包含工作日。

1 个答案:

答案 0 :(得分:0)

您可以使用JsonConvert.PopulateObject填充现有对象:

var jsonString1 = "{ Name: \"qwe\"}";
var m = JsonConvert.DeserializeObject<SubPlayground>(jsonString1);

var jsonString2 = "{ Type: \"asd\"}";
JsonConvert.PopulateObject(jsonString2, m);