Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, October 4, 2019 3:01 PM
Hi All,
I am trying to convert below JSON object to C# class. I could able to get C# equivalent for filter, but not for sort.
In the case of filter JSON object; andOr, openCondition, etc are static. Hence, I could able to generate C# class.
But for sort JSON object; accountName, and tradeDate are not static. These fields are completely as per user requirement. They may change as some other fields for some other input. Hence, I'm not understanding how can I generate C# class for this sort JSON object. Can anyone please suggest me how to do this?
{
"filter": [
{
"andOr": "",
"openCondition": false,
"columnName": "accountName",
"operator": "eq",
"value": "KATHERINE",
"closeCondition": false
}
],
"sort": {
"accountName": "asc",
"tradeDate": "desc"
},
"pageIndex": 1,
"pageSize": 75
}
All replies (3)
Friday, October 4, 2019 3:26 PM
But for sort JSON object; accountName, and tradeDate are not static. These fields are completely as per user requirement. They may change as some other fields for some other input. Hence, I'm not understanding how can I generate C# class for this sort JSON object. Can anyone please suggest me how to do this?
I recommend fixing the JSON design to make it easier.
{
"sort": [
{
"name": "accountName",
"sort": "asc",
"order": 1
},
{
"name": "tradeDate",
"sort": "desc",
"order": 2
}
]
}
Otherwise, you'll need to use a dictionary.
Saturday, October 5, 2019 9:37 AM
Hi mgebhard,
I don't have option to fix the JSON design as it's higher management decision. Could you please suggest me how can I use dictionary!
Saturday, October 5, 2019 12:42 PM
I don't have option to fix the JSON design as it's higher management decision. Could you please suggest me how can I use dictionary!
Odd that management defines your data interface. Usually developers design code.
Object model.
public class FilterData
{
public Filter[] filter { get; set; }
public Dictionary<string, string> sort { get; set; }
public int pageIndex { get; set; }
public int pageSize { get; set; }
}
public class Filter
{
public string andOr { get; set; }
public bool openCondition { get; set; }
public string columnName { get; set; }
public string _operator { get; set; }
public string value { get; set; }
public bool closeCondition { get; set; }
}
Implementation below. The code is reading the json from a file but it works the same for any stream just read the Newtonsoft documentation if you need to manually deserialize.
FilterData data = JsonConvert.DeserializeObject<FilterData>(File.ReadAllText(@"data.json"));
foreach(var item in data.sort)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
IMHO, you should fix the JSON so the data is easier to use.