使用Newtonsoft.Json合并对象时,如何忽略空字符串值? [英] When merging objects using Newtonsoft.Json, how do you ignore empty string values?

查看:444
本文介绍了使用Newtonsoft.Json合并对象时,如何忽略空字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在C#中定义为类的数据模型.我需要使用JObject.Merge合并两个对象,但是对于一个特定的属性,我需要忽略第二个对象中的空字符串值,类似于您忽略空值的方式.对此是否存在现有的属性属性,或者我是否需要以某种方式编写自己的属性?

I have a data model that is defined as a class in C#. I need to merge two objects using JObject.Merge, but in the case of one particular property I need to ignore empty string values from the 2nd object, similar to how you would ignore null values. Is there an existing attribute property for this, or do I somehow need to write my own?

void Main()
{
    string json1 = @"{ Foo: ""foo1"", Bar: ""bar1"" }";
    string json2 = @"{ Foo: ""foo2"", Bar: null }";
    string json3 = @"{ Foo: ""foo3"", Bar: """" }";

    var model1 = JObject.Parse(json1);
    var model2 = JObject.Parse(json2);
    model1.Merge(model2);
    model1.Dump();

    model1 = JObject.Parse(json1);
    model2 = JObject.Parse(json3);
    model1.Merge(model2);
    model1.Dump();
}

public class Model
{
    [JsonProperty("foo")]
    public string Foo { get ; set; }

    [JsonProperty("bar", NullValueHandling = NullValueHandling.Ignore)]
    public string Bar { get ; set; }

}

Output (1): Model.Bar = "bar1" 
Output (2): Model.Bar = "";
Desired output of (2): Model.Bar = "bar1"

好的,我意识到无法应用属性,因为我只需要使用原始json字符串作为输入.这主要是因为我的类具有带有默认值的属性.合并具有空值的类将触发默认值并最终覆盖原始值,这是我不想要的.我需要能够对类进行部分json表示并更新原始内容.很抱歉,如果一开始不清楚.我将更新最终得到的答案.

OK, I realized that attributes could not be applied since I needed to work with the raw json string only as input. This was mainly due to the fact that my classes had attributes with default values. Merging classes with empty values would trigger the defaults and end up overwriting the original, which is what I didn't want. I need to be able to take a partial json representation of a class and update the original. Sorry if that wasn't clear from the get-go. I'll update what I ended up doing an answer.

推荐答案

我操纵了JObject字典键来处理特定的条目.我觉得很脏,但是可以.我想不出一种好的"方法来做到这一点.

I manipulated the JObject dictionary keys to massage the specific entry. I feel dirty, but it works. I can't think of a "good" way to do this.

model1 = JObject.Parse(json1);
model2 = JObject.Parse(json3);
IDictionary<string, JToken> dictionary = model2;
dictionary["Bar"] = string.IsNullOrEmpty((string)dictionary["Bar"])
            ? null
            : dictionary["Bar"];
model1.Merge(model2);

这篇关于使用Newtonsoft.Json合并对象时,如何忽略空字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆