【问题标题】:Dynamic JSON parsing in. net core.net core中动态JSON解析
【发布时间】:2019-04-12 08:02:20
【问题描述】:

我们也有 N 个 JSON 参数和类属性,但是 序列化时必须动态删除类属性中不可用的 JSON 参数。

如果我使用[JsonIgnore],它只会删除值,而不是整个属性;我们需要删除整个属性。

例子:

JSON 请求:

{
    "Name":"ABC",
    "Age":26,
    "Designation":"Er",
    "Place":"Pune",
    "Gender":"Male"
}

类:

[Serializable]
public class SampleProperties
{
    [JsonProperty("Name")]
    public string Name { get; set; }
    [JsonProperty("Age")]
    public int Age { get; set; }
    [JsonProperty("Designation")]
    public string Designation { get; set; }
}

预期结果:

{
    "Name":"ABC",
    "Age":26,
    "Designation":"Er"
} 

【问题讨论】:

标签: c# json .net-core


【解决方案1】:

最好的方法是创建一个包含 30 个字段的对象并将 json 字符串反序列化为该对象
尝试这样的事情:

class MyObject
{
    public string prop1 {get;set; }
    public string prop2 {get;set; }
}

然后:

string json = "your json";
MyObject objectWith30Fields = JsonConvert.DeserializeObject<MyObject>(json);

【讨论】:

    【解决方案2】:

    您可以像下面的代码一样设置NullValueHandling,您可以在Newtonsoft.Json 的documentation 或此link 中看到,此外,您可以使用ExpandoObject(),如您在此看到的link

    public class Movie
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public string Classification { get; set; }
        public string Studio { get; set; }
        public DateTime? ReleaseDate { get; set; }
        public List<string> ReleaseCountries { get; set; }
    }
    
    Movie movie = new Movie();
    movie.Name = "Bad Boys III";
    movie.Description = "It's no Bad Boys";
    
    string included = JsonConvert.SerializeObject(movie,
        Formatting.Indented,
        new JsonSerializerSettings { });
    
    // {
    //   "Name": "Bad Boys III",
    //   "Description": "It's no Bad Boys",
    //   "Classification": null,
    //   "Studio": null,
    //   "ReleaseDate": null,
    //   "ReleaseCountries": null
    // }
    
    string ignored = JsonConvert.SerializeObject(movie,
        Formatting.Indented,
        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    
    // {
    //   "Name": "Bad Boys III",
    //   "Description": "It's no Bad Boys"
    // }
    

    更多关于ExpandoObject

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 2018-02-12
      • 2016-10-16
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多