w0f
w0f

Reputation: 958

C# Parsing JSON arrays without property names as objects

I am using an API that returns a bunch of order data as an array of strings.

"orders": [
    //[ price, size, order_id ]
    [ "295.96","0.05088265","3b0f1225-7f84-490b-a29f-0faef9de823a" ],
    ...
]

I need to use Json.Net to parse it to an object of the following format:

public class Order
{
    public decimal price { get; set; }
    public decimal size { get; set; }
    public Guid order_id { get; set; }
}

How can I achieve this? I know how to use Json.NET to deserialize an object so I end up with a single property orders of type string array, but is there any way to skip that and have it just directly map to an object instance instead?

Upvotes: 3

Views: 3991

Answers (1)

Phi
Phi

Reputation: 514

It seems that your string is not a valid json, when I try to parse here I have the following error:

Expecting object or array, not string.[Code 1, Structure 1]

But, I have found a way to deserialize it. I see that your json is an array, so, we can parse as JArray and removing "orders": text:

JsonConvert.DeserializeObject<JArray>(json.Replace("\"orders\":", string.Empty));

Now, we have an array but I think is not possible to do an explicit cast to Order or List<Order> type, and the answer is that we need to iterate the JArray:

List<Order> orders = new List<Order>();

foreach (var item in arrayListed)
{
    Order order = new Order();
    order.price = (decimal)item[0];
    order.size = (decimal)item[1];
    order.order_id = (Guid)item[2];
    orders.Add(order);
}

Here is the demostration and its results.

Upvotes: 1

Related Questions