How can I express the following JSON to a C# class? The item numbers (oi_abc, oi_def) will always be unique values I have to pass into the POST. Thanks for any help.
{
"availabilities": {
"oi_abc": {
"available_quantity": 0,
"discontinued": true
},
"oi_def": {
"available_quantity": 4,
"discontinued": false,
"backordered_until": "2019-03-15T00:10:00.000Z"
}
}
}
CodePudding user response:
You should probably use a dictionary for availabilities
?
Something like:
public class Model {
public Dictionary<string, AvailabilityInfo> availabilities { get; set; }
}
public class AvailabilityInfo {
public int available_quantity { get; set; }
public boolean discontinued { get; set; }
public DateTime? backordered_until { get; set; }
}
CodePudding user response:
better to use c# standarts of naming
public partial class Data
{
[JsonProperty("availabilities")]
public Dictionary<string,Availability> Availabilities { get; set; }
}
public partial class Availability
{
[JsonProperty("available_quantity")]
public long AvailableQuantity { get; set; }
[JsonProperty("discontinued")]
public bool Discontinued { get; set; }
[JsonProperty("backordered_until")]
public DateTimeOffset BackorderedUntil { get; set; }
}
and code
using Newtonsoft.Json;
Data data = JsonConvert.DeserializeObject<Data>(json);
but in some cases it is easier to use list instead of dictionary, so I would recommend this code
var jsonParsed=JObject.Parse(json);
List<Availability> availabilities = ((JObject)jsonParsed["availabilities"]).Properties()
.Select(x => new Availability {
Name = x.Name, Available = x.Value.ToObject<Available>()
}).ToList().Dump();
result
[
{
"Name": "oi_abc",
"Available": {
"AvailableQuantity": 0,
"Discontinued": true,
"BackorderedUntil": "0001-01-01T00:00:00 00:00"
}
},
{
"Name": "oi_def",
"Available": {
"AvailableQuantity": 0,
"Discontinued": false,
"BackorderedUntil": "0001-01-01T00:00:00 00:00"
}
}
]
classes
public partial class Availability
{
public string Name { get; set; }
public Available Available { get; set; }
}
public partial class Available
{
public long AvailableQuantity { get; set; }
public bool Discontinued { get; set; }
public DateTimeOffset BackorderedUntil { get; set; }
}
CodePudding user response:
public class OiAbc
{
public int available_quantity { get; set; }
public bool discontinued { get; set; }
}
public class OiDef
{
public int available_quantity { get; set; }
public bool discontinued { get; set; }
public DateTime backordered_until { get; set; }
}
public class Availabilities
{
public OiAbc oi_abc { get; set; }
public OiDef oi_def { get; set; }
}
CodePudding user response:
You can pass this json as a object. To that, create a classes like below. Otherwise send as json string and deserialize in c# method
public class availabilities
{
public oiabc oi-abc {get;set;}
}
public class oiabc
{
public int available_quantity {get;set;}
}