3

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?

w0f
  • 908
  • 9
  • 23
  • I think you might need to write your own converter because there's no way without properties that you can map the data to the properties in your class. If you know the order will always be the same then you can just assign each value yourself. See the answer below for more information: https://stackoverflow.com/a/8031283/3492988 – mdon88 Sep 06 '17 at 23:14
  • Not sure what you mean by *just directly map to an object instance instead* - That is exactly what .net json does for you. `var orders = JsonConvert.Deserialize>(jsonString)` would return a collection of Order "instances" created for you. – Jaya Sep 06 '17 at 23:54
  • You could use `ObjectToArrayConverter` from [C# JSON.NET - Deserialize response that uses an unusual data structure](https://stackoverflow.com/q/39461518/3744182) to deserialize that JSON. In fact, this question may be a duplicate of that. Agree? – dbc Sep 07 '17 at 05:29

1 Answers1

1

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.

Phi
  • 504
  • 3
  • 13
  • 30