Mystika Mystika - 3 months ago 12
JSON Question

how to combine two same class object into one?

I made a one class that named Phrases that includes some strings and integers.

public class Phrases {
public class PhraseData {
public string text { get; set; }
public string htmlColor { get; set; }
public int position { get; set; }
}

public PhraseData intro { get; set; }
public PhraseData credit { get; set; }
public PhraseData general { get; set; }
/* and more PhraseDatas... */
}

/* ... */


and I have a two json file. one is only have text data of PhraseData, another one have a every data except text data. so If I deserialize these json files. I'll get two Phrases class objects like this.

Phrases onlyTextFilled;
Phrases everyDataFilledExceptText;


I want to combine these two class objects into one. there is any good way to solve this problem?

help me guys!

Answer

Quick and dirty. Overload the '+' operator. For the inner class and the main one. Also add attributes to ignore default and null values for your properties (if using Newtonsoft.Json for instance). Another wild thought, you could use the decorator pattern.

public class Phrases
{
    public class PhraseData
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 1, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string text { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 2, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string htmlColor { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, Order = 3, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int position { get; set; }

        public static PhraseData operator + (PhraseData pd1, PhraseData pd2)
        {
            var pd = new PhraseData();
            pd.text = (pd1.text == null) ? pd2.text : pd1.text;
            pd.htmlColor = (pd1.htmlColor == null) ? pd2.htmlColor : pd1.htmlColor;
            pd.position = (pd1.position == 0) ? pd2.position : pd1.position;
            return pd;
        }
    }

    public PhraseData intro { get; set; }
    public PhraseData credit { get; set; }
    public PhraseData general { get; set; }

    public static Phrases operator + (Phrases p1, Phrases p2)
    {
        return new Phrases() { 
            intro = p1.intro + p2.intro,
            credit = p1.credit + p2.credit,
            general = p1.general + p2.general
        };
    }
}