Alexander Man
Alexander Man

Reputation: 63

Convert JToken To List of objects

I Have json string from site like here:

{
"bids": [["6500.12", "0.45054140"],
     ["6500.11", "0.45054140"]],  //[price,size]
 "asks": [["6500.16", "0.57753524"],
     ["6500.15", "0.57753524"]] 
}

With the help of Newtonsoft Json I tried to get JToken:

var content = JObject.Parse(responce)["data"].Children<JProperty>().FirstOrDefault(x=>x.Name=="asks").Value;

Then, I would like to convert this JToken to this object, but can`t understand how to

        public class PriceValue
        {
            public string Price { get; set; }

            public string Value { get; set; }
        }

        public List<PriceValue> Sell { get; set; }

        public List<PriceValue> Buy  { get; set; }

Upvotes: 1

Views: 11545

Answers (1)

Krishna Varma
Krishna Varma

Reputation: 4250

You can try JObject and JArray

var json = File.ReadAllText(filepath);

var jObject = JObject.Parse(json);

var bids = JArray.Parse(jObject["bids"].ToString());    
var Sell = bids.Select(x => 
                new PriceValue
                {
                    Price = x[0].ToString(),
                    Value = x[1].ToString()
                })
                .ToList();

var asks = JArray.Parse(jObject["asks"].ToString());
var Buy = asks.Select(x =>
                new PriceValue
                {
                    Price = x[0].ToString(),
                    Value = x[1].ToString()
                })
                .ToList();

Upvotes: 2

Related Questions