0

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!

3
  • 1
    Don't use string manipulation, create a Type that models the response and deserialize the json into your object with Json.Net Commented Feb 15, 2018 at 13:14
  • The reponse format is "JSON". Look it up. For .Net I would use Newtonsoft Commented Feb 15, 2018 at 13:18
  • Cheers for the responses. Ill check Newstonsoft out right away. Commented Feb 15, 2018 at 13:18

2 Answers 2

3

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

var lastValue = JObject.Parse(currentXRPPrice.Text).SelectToken("last").ToString();
Sign up to request clarification or add additional context in comments.

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.