When merging objects using Newtonsoft.Json, how do you ignore empty string values?

I have a data model that is defined as a class in C #. I need to combine two objects using JObject.Merge, but in the case of one specific property, I need to ignore the empty values ​​of the string from the second object, similar to how you ignore null values. Is there an existing attribute property for this, or do I need to somehow 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"

EDIT: , , , json . - , . , . json- . , . , , .

+1
2

JObject . , . "" .

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);
0

JObject, , :

public static class JsonExtensions
{
    public static void RemovePropertiesByValue(this JToken root, Predicate<JValue> filter)
    {
        var nulls = root.DescendantsAndSelf().OfType<JValue>().Where(v => v.Parent is JProperty && filter(v)).ToList();
        foreach (var value in nulls)
        {
            var parent = (JProperty)value.Parent;
            parent.Remove();
        }
    }

    public static IEnumerable<JToken> DescendantsAndSelf(this JToken node)
    {
        if (node == null)
            return Enumerable.Empty<JToken>();
        var container = node as JContainer;
        if (container != null)
            return container.DescendantsAndSelf();
        else
            return new [] { node };
    }
}

:

        model2.RemovePropertiesByValue(v => v.Type == JTokenType.String && string.IsNullOrEmpty((string)v.Value));

, , , , . ?

0

Source: https://habr.com/ru/post/1693782/


All Articles