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?

3
  • 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: stackoverflow.com/a/8031283/3492988 Commented Sep 6, 2017 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<IEnumerable<Order>>(jsonString) would return a collection of Order "instances" created for you. Commented Sep 6, 2017 at 23:54
  • You could use ObjectToArrayConverter<Order> from C# JSON.NET - Deserialize response that uses an unusual data structure to deserialize that JSON. In fact, this question may be a duplicate of that. Agree? Commented Sep 7, 2017 at 5:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.