简体   繁体   中英

C# - deserialize json

I'm trying to write a trading bot as a learning experience (don't worry, I won't use it). I am trying to deserialize the incoming data with no luck. It's my first time working with json in C# but I have done so in other languages, certainly not very good at it though.

I created a class that looks like this:

public class Coin
    {
        public string symbol { get; set; }
        public double price {get;set;}
    }

I am fetching and reading the data like this:

using (WebClient w = new WebClient())
            {
                try
                {
                var json = w.DownloadString("https://api.binance.com/api/v3/ticker/price");
                int length = json.Length;
                string newJson = json.Substring(1, length-2);
//had to create new string because having [] made it crash
                Coin coin = JsonConvert.DeserializeObject<Coin>(newJson);
                Console.Write(coin); // this does not print anything
            }catch(JsonReaderException e){}
           }

Incoming data looks like this (or just follow the link):

{"symbol":"ETHBTC","price":"0.07190100"},{"symbol":"LTCBTC","price":"0.01298100"}

Now, I'm trying to only get one of them, but I am getting all. First of all I'm guessing there's something wrong with my Coin class and second I don't know how to access just one of them.

Thanks

You are getting array of objects, but you are trying to deserialise into a single object. There is a reason for [] symbols. Don't remove them. Instead serialise into Coin[] and then take .FirstOrDefault() from that array.

Something like this:

using System.Linq;

var json = w.DownloadString("https://api.binance.com/api/v3/ticker/price");
var coins = JsonConvert.DeserializeObject<Coin[]>(json);
var firstCoin = coins.FirstOrDefault();
if (firstCoin != null)
{
     Console.Write($"Symbol: {firstCoin.symbol}; Price: {firstCoin.price}");
}

I don't see anything wrong with your Coin class. Secondly, what I advice you to do is to deserialize the JSON into a List of coins.

List<Coin> coins = new List<Coin>();
coins = JsonConvert.DeserializeObject<List<Coin>>(newJson);

In your code you deserialized multiple Coin-objects and you wanted to store them in a variable that holds one Coin-object. That is why I adviced to make a list of objects, so that multiple Coin-objects can be stored.

You can then get one item of the list by index.

// This returns the first value
var oneItem = coins[0]

I hope this did the trick!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM