Get value from Json url with a changing variable

Viewed 64

I want to get the price of any crypto coin from BitZ api. I have the code like this:

string coinName;
string jsonURL = "https://apiv2.bitz.com/Market/coinRate?coins=" + coinName;

I will give the variable coinName the value I want for example coinName = "btc" and I want the price in USDT The problem here is the Json structure it contains the coin name I will end up with tons of code lines if do this for every coin,

    public class Btc
    {
        public string usdt { get; set; }
    }

    public class Data
    {
        public Btc btc { get; set; }
    }

    public class Root
    {
        public int status { get; set; }
        public string msg { get; set; }
        public Data data { get; set; }
        public int time { get; set; }
        public string microtime { get; set; }
        public string source { get; set; }
    }

Unlike Bittrex api for example which is easier to read using JsonDotNet asset from unity store and :

BittrexJsonUrl = "https://api.bittrex.com/api/v1.1/public/getticker?market=USDT-" + coinName;

and then I use this code to get the data:

private IEnumerator GetData()
    {

        /////bittrex
            UnityWebRequest request = UnityWebRequest.Get(BittrexJsonUrl);
            yield return request.SendWebRequest();
            if (request.error == null)
            {
                Bittrex_proccessJsonData(request.downloadHandler.text);
            }
            else
            {
                    Debug.Log("Something went wrong!!");
                }
}

private void Bittrex_proccessJsonData (string _url) {

    var _bittrexJsonData = JsonConvert.DeserializeObject<BittrexJsonData>(_url);

    bittrexPrice = _bittrexJsonData.result.Last;
}

this works perfectly with with bittrex's Json structure, since it doesnt contain the coin name all I do is change the Json URL. Now I want to do like the same thing for BitZ's if you have any idea how to please help :) thank you in advance.

1 Answers

For such thing you could use good old SimpleJson.

Here you don't need to implement the entire c# structure but rather access the data field by field via it's ID. You can imagine it like a nested Dictionary like thing.

Simply create that file with given content from the link somewhere in your project and do e.g.

var json = JSON.Parse(the_JSON_string);
var usdt = json["Data"]["bst"]["usdt"].AsFloat;        
Related