Search code examples
c#winformshttpsubstringhttpwebrequest

Substring a HTTP Response into a Variable [C# Winforms]


Im trying to get a cryptocurrency last price value from a HTTP API:

The following piece of code:

 // Create the web request  
 HttpWebRequest request = 
 WebRequest.Create("APISITE") as 
 HttpWebRequest;

        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream  
            StreamReader reader = new StreamReader(response.GetResponseStream());

            // Console application output  
            currentXRPPrice.Text = (reader.ReadToEnd());
        }

Gives me the following response which is correct:

{"high": "1.15600", "last": "1.08269", "timestamp": "1518697359", "bid": "1.08034", "vwap": "1.09634", "volume": "40858340.75727354", "low": "1.03051", "ask": "1.08269", "open": "1.13489"}

What I want is just the value of "last" which is "1.08269". I have tried using this post: [link] (Remove characters after specific character in string, then remove substring?) which has worked wonders for me on previous projects. But I cant seem to figure out where I am going wrong.

Iv tried below to get the value of "last" but its completely wrong, I have tried many of the different combinations to get it right but its not working to show me just the value for "Last".

        response = currentXRPPrice.Text;
        response = response.Remove(response.LastIndexOf(":") + 1);
        profitLossText.Text = response; //Still wrong tried 4 combinations none work.

Thanks for any help!


Solution

  • You need to install Newtonsoft.Json from Nuget packages and use Parse method from JObject:

    var lastValue = JObject.Parse(currentXRPPrice.Text).SelectToken("last").ToString();