Search code examples
c#jsonserializationjson.netjsonserializer

JSON serialization using newtonsoft in C#


I have the following model structure.

 public class ReferenceData
    {
        public string Version { get; set; }

        public List<DataItem> Data { get; set; }
    }


    public class DataItem
    {
        public Dictionary<string, string> Item { get; set; }
    }

In the dictionary i'm adding the key value pair and serializing with KeyValuePairConverter setting.

var settings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters = new List<JsonConverter>() { new KeyValuePairConverter() }
                };

var object =  Newtonsoft.Json.JsonConvert.SerializeObject(
                    referenceData,
                    Formatting.None,
                    settings
                    );

And the output is,

 {  
       "data":[  
          {  
             "item":{  
                "ShortDescription":"Lorem ipssumm",
                "Title":"some text",
                "PlanType":"ZEROP",
             }
          },
           {  
             "item":{  
                "ShortDescription":"Lorem ipssumm",
                "Title":"some text",
                "PlanType":"ZEROP",
             }
          },
          {  
             "item":{  
                "ShortDescription":"Lorem ipssumm",
                "Title":"some text",
                "PlanType":"ZEROP",
             }
          }
       ]
    }

If we don't want item to be showed in the serialized string, what setting needs to be done in JsonSerializerSettings or is there any other way to do that.

Please note that i can not change the model structure as it is required.

output should be :

{  
   "data":[  
      {  
         "ShortDescription":"Lorem ipssumm",
         "Title":"some text",
         "PlanType":"ZEROP"
      },
      {  
         "ShortDescription":"Lorem ipssumm",
         "Title":"some text",
         "PlanType":"ZEROP"
      },
      {  
         "ShortDescription":"Lorem ipssumm",
         "Title":"some text",
         "PlanType":"ZEROP"
      }
   ]
}

Solution

  • You do not need nested generic collections if you use Json.NET 5.0 release 5 or later version. You can use JsonExtensionDataAttribute so that Item dictionary's keys and values will be serialized as a part of parent object.

    public class ReferenceData
    {
        public string version { get; set; }
        public List<DataItem> data { get; set; }
    }
    
    public class DataItem
    {   
        [JsonExtensionData]
        public IDictionary<string, object> item { get; set; }
    }
    
    // ...
    
    var referenceData = new ReferenceData {
        version = "1.0",
        data = new List<DataItem> {
            new DataItem {
                item = new Dictionary<string, object> {
                    {"1", "2"},
                    {"3", "4"}
                }
            },
            new DataItem {
                item = new Dictionary<string, object> {
                    {"5", "8"},
                    {"6", "7"}
                }
            }
        }
    };
    
    Console.WriteLine(JsonConvert.SerializeObject(referenceData));
    

    Pay attention that you need Dictionary<string, object> instead of Dictionary<string, string>.

    Here is the result I get:

    {
      "version": "1.0",
      "data": [
        {
          "1": "2",
          "3": "4"
        },
        {
          "5": "8",
          "6": "7"
        }
      ]
    }
    

    Obviously, you can remove Version property to get the expected result.

    Read more here: http://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension-data