Tantrix1
Tantrix1

Reputation: 89

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!

Upvotes: 0

Views: 1061

Answers (2)

kasuocore
kasuocore

Reputation: 99

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

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

Upvotes: 3

Mjollnir951
Mjollnir951

Reputation: 25

First of all, if you have Json string, you can define a class which represent this object and then you just deserialize this string to object using generic method.

var jsonString = currentXRPPrice.Text;
var deserializedResponse = JsonConvert.DeserializeObject<ReponseType>(jsonString);
var lastValue = deserializedResponse.Last;

public class ReponseType
{
    ...
    public float Last { get; set; }
    ...
}

You can do it by Regex too:

var lastValue = Regex.Match(jsonString, @"last\": \"(\\d+\\.\\d+)"").Groups[0];

Upvotes: 0

Related Questions