2

I am working on retrieving USD -> GBP exchange rates from CurrencyLayer using a C# script task in SSIS. I have used the following code:

string url = Dts.Variables["User::CurrencyLayerURL"].Value.ToString();
WebClient wc = new WebClient();
var jsonString = wc.DownloadString(url);

To successfully retrieve the following JSON string:

{  
   "success":true,
   "terms":"https:\/\/currencylayer.com\/terms",
   "privacy":"https:\/\/currencylayer.com\/privacy",
   "historical":true,
   "date":"2015-11-28",
   "timestamp":1448755199,
   "source":"USD",
   "quotes":{  
      "USDGBP":0.66527
   }
}

However, I am not sure at this point how to retrieve just the 0.66527 value that corresponds to the "USDGBP" rate and pass it to a variable. I have seen a number of suggestions to use the JSON.net library, but I am not able to add any third-party libraries to this project. Any help would be appreciated.

EvanMPW
  • 351
  • 1
  • 6
  • 15
  • You could keep it simple and just use string parsing to get it out. When your package is mostly C# code you might want to reconsider whether it should be a package. – Nick.Mc Nov 29 '15 at 22:45

3 Answers3

4

You can use the JsonValue class from System.Json Namespace.

JsonValue value = JsonValue.Parse(jsonString);
var quote =  (string)result["quotes"]["USDGBP"];

Or you could use the JavaScriptSerializer from System.Web.Script.Serialization

var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<ExpandoObject>(jsonString);
var quote = result.quotes.USDGBP;

Or in Json.Decode from System.Web.Helpers

Var result = Json.Decode(jsonString);
var quote = result.quotes.USDGBP;
swestner
  • 1,881
  • 15
  • 19
0

Parse your json object using JSON.NET:

dynamic d = JObject.Parse(jsonString );
Console.WriteLine(d.quotes.USDGBP);
KiwiPiet
  • 1,304
  • 14
  • 21
0

You can use JavaScriptSerializer You can add Syatem.Web.Extensions namespace reference.

    var serializer = new JavaScriptSerializer();
     //Serialize
     var serializedResult = serializer.Serialize(Object);
     //Deserialize
   var deserializedResult = serializer.Deserialize<OutputObjectType>(jsonString);
Kalamarico
  • 5,466
  • 22
  • 53
  • 70