I have a memory stream of data I have received from Poloniex's API. https://docs.poloniex.com/#ticker-data
The data in the API looks in the format below:
[
1002,
null,
[
149,
"382.98901522",
"381.99755898",
"379.41296309",
"-0.04312950",
"14969820.94951828",
"38859.58435407",
0,
"412.25844455",
"364.56122072",
0,
0
]
]
I can see that this is valid json on https://jsonlint.com/
My end goal is I want to deserialize this into an object in C# which I can send elsewhere.
I've never seen JSON like this before and unsure how I would deserialize this structure into my own model. I'm used to see JSON as keyvaluepairs
I've deserialized into a JArray and going from there but I'm unsure of the best approach.
var deserialized =
(JArray)_serializer.Deserialize(new JsonTextReader(new StreamReader(stream))
{
CloseInput = false
});
What would be the best way to do this?
Example model structure to deserialize into:
public class PoloniexResponseDataRoot
{
public List<PoloniexResponseDataParent> Children { get; set; }
}
public class PoloniexResponseDataParent
{
public int ChannelNumber { get; set; }
public int? OtherNumber { get; set; }
public List<PoloniexResponseDataChild> Children { get; set; }
}
public class PoloniexResponseDataChild
{
public object Data { get; set; }
}
Thanks
If your structure is as simple as the one in your example and that the first 2 numbers always represent ChannelNumber
and OtherNumber
followed by 1 level array, then you can do something like this:
private static PoloniexResponseDataParent Parse(JArray objects)
{
var parent = new PoloniexResponseDataParent();
var channelNumber = objects[0];
var otherNumber = objects[1];
var children = objects[2];
parent.ChannelNumber = Convert.ToInt32(channelNumber);
parent.OtherNumber = (otherNumber as JValue).Value<int?>();
parent.Children = children.Select(item => new PoloniexResponseDataChild
{
Data = item switch
{
JValue jValue => jValue.Value,
_ => throw new ArgumentOutOfRangeException(nameof(item))
}
}).ToList();
return parent;
}
var jArray = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(jsonStr);
var parent = Parse(jArray);