简体   繁体   中英

I need help to parse a value from a JSON-string from an url to float/double

I am making a small currency converter in C#.

I have an URL containing a JSON string (api) holding the currency exchange rate, but I have no idea how to convert/parse the exchange rate (to float or double) so I can use it in my program.

Any suggestions how to start? Can i get the value "v" in the URL into a float or double?

This is my URL: http://rate-exchange.appspot.com/currency?from=USD&to=SEK&q=1

Thanks in advance

Max

Please check at: http://json2csharp.com/

Sample class generated below:

public class RootObject
{
    public string to { get; set; }
    public double rate { get; set; }
    public string from { get; set; }
    public double v { get; set; }
}

As to how to do it, check here .

The System.Double and System.Single structs contain static methods for parsing strings to doubles and floats respectively. You might also look into the System.Convert class.

Lastly, JSON can be parsed without the need for any third-party libraries.

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization; //Add a reference to System.Web.Extensions.dll to your project.

class Program
{
    static void Main()
    {
        string jsonString;

        using( WebClient client = new WebClient() )
        {
            jsonString = client.DownloadString( "http://rate-exchange.appspot.com/currency?from=USD&to=SEK&q=1" );
        }

        var serializer = new JavaScriptSerializer();
        var jsonObject = serializer.Dezerialize<Dictionary<string, object>>( jsonString );

        double rate = Double.Parse( jsonObject["rate"] );
        double v    = Double.Parse( jsonObject["v"] );
    }
}

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