I am serializing data from a database into JSON format using JSON.Net. But I am not able to get the result I expect.
I have to create JSON objects according to certain conditions like if my data for datamap
is null then it should not be included in the JSON, and if it is not null then it should be included.
public class DatamapKey
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapKeyFields = new Dictionary<string, JToken>();
}
public class DatamapKey1
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapKey1Fields = new Dictionary<string, JToken>();
}
public class DatamapItem
{
[JsonExtensionData]
public Dictionary<string, JToken> DatamapItemFields = new Dictionary<string, JToken>();
public DatamapKey datamapKey { get; set; }
public DatamapKey1 datamapKey1 { get; set; }
}
public class RootObject
{
public List<DatamapItem> datamapItems { get; set; }
}
Output JSON:
{
"datamapItems": [
{
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {},
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"datamapKey": {},
"datamapKey1": {},
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {
"module": 1,
"id": 1391
},
"paramName": "VE8321C",
"min": "0",
"max": "40"
}
]
}
Expected Output:
{
"datamapItems": [
{
"paramName": "VE8321C",
"datamapKey": {
"module": 1,
"id": 1391
},
"min": "0",
"max": "40"
},
{
"paramName": "VE8321C",
"min": "0",
"max": "40"
},
{
"paramName": "VE8321C",
"datamapKey": {
"module": 1,
"id": 1391
},
"datamapKey1": {
"module": 1,
"id": 1391
},
"min": "0",
"max": "40"
}
]
}