using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
public static void Main()
var item1 = new DatamapItem();
item1.datamapKey.Add("module", 1);
item1.datamapKey.Add("id", 1391);
item1.DatamapItemFields.Add("paramName", "VE8321C");
item1.DatamapItemFields.Add("min", "0");
item1.DatamapItemFields.Add("max", "40");
var item2 = new DatamapItem();
item2.DatamapItemFields.Add("paramName", "VE8321C");
item2.DatamapItemFields.Add("min", "0");
item2.DatamapItemFields.Add("max", "40");
var item3 = new DatamapItem();
item3.datamapKey.Add("module", 1);
item3.datamapKey.Add("id", 1391);
item3.datamapKey1.Add("module", 1);
item3.datamapKey1.Add("id", 1391);
item3.DatamapItemFields.Add("paramName", "VE8321C");
item3.DatamapItemFields.Add("min", "0");
item3.DatamapItemFields.Add("max", "40");
var root = new RootObject
datamapItems = new List<DatamapItem> { item1, item2, item3 }
var settings = new JsonSerializerSettings
ContractResolver = IgnoreEmptyEnumerablesResolver.Instance,
Formatting = Formatting.Indented
var json = JsonConvert.SerializeObject(root, settings);
public Dictionary<string, JToken> DatamapItemFields { get; set; }
public Dictionary<string, JToken> datamapKey { get; set; }
public Dictionary<string, JToken> datamapKey1 { get; set; }
DatamapItemFields = new Dictionary<string, JToken>();
datamapKey = new Dictionary<string, JToken>();
datamapKey1 = new Dictionary<string, JToken>();
public List<DatamapItem> datamapItems { get; set; }
public class IgnoreEmptyEnumerablesResolver : DefaultContractResolver
public static readonly IgnoreEmptyEnumerablesResolver Instance = new IgnoreEmptyEnumerablesResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
var property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType != typeof(string) &&
typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
property.ShouldSerialize = instance =>
IEnumerable enumerable = null;
switch (member.MemberType)
case MemberTypes.Property:
.GetProperty(member.Name)
.GetValue(instance, null) as IEnumerable;
.GetValue(instance) as IEnumerable;
return enumerable.GetEnumerator().MoveNext();