|
Thanks again for all of your help, and your contribution to this project.
EF is definitely the way to go.
I really do appreciate the assistance.
modified 1-Jun-14 23:15pm.
|
|
|
|
|
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
Do you know why?
|
|
|
|
|
I'd bet it some kind of combination of characters that is considered unsecure. Can you post a sample of data you're trying to parse?
|
|
|
|
|
Hi Mikhail and thanks for your quick answer. I followed your post step by step (I am new..)
this is the value of json_data:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Open Exchange Rates</title>
<meta name="description" content="Free, hourly-updated exchange rates - a simple, accurate, open-source JSON API. Free for personal use, a bargain for everybody else.">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:400,700">
<link rel="stylesheet" type="text/css" href="/css/main.min.0006.css" />
<link href="/favicon.ico" type="image/x-icon" rel="shortcut icon" />
<link rel="canonical" href="https://openexchangerates.org/"/>
<script>var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-31023525-1']);_gaq.push(['_setDomainName', 'openexchangerates.org']);_gaq.push(['_setAllowLinker', true]);_gaq.push(['_trackPageview']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>
</head>
<body class="hfeed home">
<header class="site-header cf" role="banner">
<div class="container">
<div class="site-logo">
<a href="/" title="Exchange Rates API, JSON format, for Developers"><span class="star">$</span> open exchange rates</a>
</div>
<ul class="site-nav inline-block-list">
<li>
<a href="/about">About</a>
</li>
<li>
<a href="/showcase">Showcase</a>
</li>
<li>
<a href="/documentation">Documentation</a>
</li>
<li>
<a class="get-started" href="/signup">Get Your App ID</a>
</li>
</ul>
</div>
</header>
<div class="site-promo">
<div class="container">
<h1>
Real-time exchange rates &<br/>
currency conversion JSON API
</h1>
<p class="description">
Simple, reliable rates for developers – with 165 currencies and more.
</p>
<div class="cta-option">
<a class="btn-download" href="/signup" title="Get Your Open Exchange Rates App ID here">
<strong>Get Instant Access</strong>
</a>
</div>
<div class="example">
<pre class="latest-json prettyprint inactive"><div class="toggle">{ <a href="#" title="Click to view an example API response">→ click to test API response</a> }</div><div class="result" style="display:none">/* latest.json (32 mins ago) */
{
"timestamp": 1392044462,
"base": "USD",
"rates": {
"AED": 3.67323,
"AFN": 56.517325,
"ALL": 102.958999,
"AMD": 414.031002,
/* <a target="_blank" href="/currencies" title="Click to view the list of currencies supported by Open Exchange Rates">165 currencies</a> */
"YER": 214.919,
"ZAR": 11.1218,
"ZMK": 5253.075255,
"ZMW": 5.602652,
"ZWL": 322.355006
}
}<div style="display:none;" class="pull-right"><a href="" title=""><small>more examples →</small></a></div></div></pre>
</div>
</div>
</div>
<aside class="trusty aside">
<div class="container">
<div class="trusted-by">Trusted by thousands – including:</div>
<ul class="inline-block-list">
<li><img src="/img/logos/shopify.gif" title="Shopify - the powerful ecommerce website solution, providing everything you need to create an online store" alt="Shopify"></li>
<li><img style="height: 42px; margin:-6px -11px -4px -14px" src="/img/logos/etsy.png" title="Etsy - Your place to buy and sell all things handmade, vintage, and supplies" alt="Etsy"></li>
<li><img src="/img/logos/fab.gif" title="Fab.com - discover everyday design products at great prices, connect with the world's most exciting designers, and share your favorite design inspirations." alt="Fab.com"></li>
<li><img style="margin: 0 -6px 0 -7px;" src="/img/logos/justgiving.gif" title="JustGiving - Online fundraising donations and ideas" alt="JustGiving"></li>
<li><img style="margin: -7px -2px 0 -3px" src="/img/logos/braintree.gif" title="Braintree Payments - Accept payments in your app or website" alt="Braintree"></li>
<li><img style="margin: 2px 0px 0 -4px; height: 28px" src="/img/logos/wego.gif" title="Wego Flight Search - Save time, pay less, travel more" alt="Wego"></li>
<li><img style="margin: 0px -7px 0 -5px; height: 19px" src="/img/logos/coinbase.gif" title="Coinbase - Your Hosted Bitcoin Wallet" alt="Coinbase"></li>
<li><img style="height: 18px; margin: 0 -2px 0 0;" src="/img/logos/flattr.gif" title="Flattr Social Micropayments - Big change through small donations" alt="Flattr"></li>
<li><img style="margin:-6px 0 0 -3px" src="/img/logos/woocommerce.gif" title="WooCommerce by WooThemes - An e-commerce toolkit that helps you sell anything." alt="WooCommerce"></li>
</ul>
</div>
</aside>
<div class="site-content">
<div class="container">
<div class="alert alert-block alert-danger" style="text-align:center;">
<h4>Notice: App ID Required</h4>
As per public notices beginning June 2012, an App ID is required to access the Open Exchange Rates API.<br/>
It's free for personal use, a bargain for your business. You can <a href="/signup" title="Get Your Open Exchange Rates App ID here"><strong>sign up here »</strong></a>
</div>
<hr/>
<br>
<p class="clearfix alert alert-success" style="text-align:left">
<strong>Monday 10th February: </strong>
Looking for an alternative to the shut-down iGoogle calculator/exchange rate service? Open Exchange Rates features up-to-date and historical rates for 165 world currencies, in a simple and reliable JSON API. Get started in minutes! </p>
<div class="lead">
<h2>Simple, Fast & Accurate Exchange Rates API</h2>
<div class="grid">
<div class="grid-cell">
<h3><span class="star">★ </span> Real-time & Historical Rates</h3>
<p>For maximum consistency and unbiased data, <strong>exchange rates for 165 world currencies</strong> are tracked from multiple sources and blended algorithmically, with historical data back to 1999.</p>
</div>
<div class="grid-cell">
<h3><span class="star">★ </span> Suitable For All Applications</h3>
<p>The <strong>exchange rates API</strong> is delivered in simple and portable JSON format with <strong>HTTPS</strong> and <strong>JSONP</strong> support, for fast and easy use in any language. Check out the <a href="/showcase" title="Showcase of Open Exchange Rates Apps">showcase</a> for examples!</p>
</div>
</div>
<br/>
<h2>Why use Open Exchange Rates?</h2>
<p class="in-the-wild">Live and historical exchange rates for 165 currencies in a simple JSON API.</p>
<p class="in-the-wild">Unbiased consistency, fantastic email support and documentation.</p>
<p class="in-the-wild">Free for personal use, a bargain for your business.</p>
<div class="cta-option">
<a class="btn-download" href="/signup" title="Get Your Open Exchange Rates App ID here">
<strong>Get Started Here</strong>
</a>
</div>
</div>
</div>
</div>
<footer class="site-footer" role="contentinfo">
<div class="container">
<p>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="inline" data-via="josscrowcroft" data-url="http://openexchangerates.org/" data-text="Open Exchange Rates API: realtime currency conversion data for developers">Tweet</a>
<g:plusone size="medium" annotation="none"></g:plusone>
<a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://openexchangerates.org"></a><noscript><a href="http://flattr.com/thing/622410/Open-Exchange-Rates-API" target="_blank"><img src="https://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript>
</p>
<p>Any questions? Please <a href="mailto:support@openexchangerates.org" title="Contact Us" rel="nofollow" target="_blank">get in touch</a>!</p>
<p style="color:#777">
<a href="/signup" title="Open Exchange Rates - App ID Signup">Sign up</a>
| <a href="/login" title="Open Exchange Rates Account Login">Log in</a>
| <a href="/faq" title="Open Exchange Rates FAQ">FAQ</a>
| <a href="/contact" title="Contact Open Exchange Rates">Contact</a>
| <a href="/sitemap" title="Open Exchange Rates Sitemap">Sitemap</a>
<br/>
</p>
<p><a href="http://my.tsohost.com/aff.php?aff=1448" title="Best UK WordPress and Shared Hosting" target="_blank"><img src="/img/tsohost-brand.gif" alt="TSOHost - UK Hosting Provider" /></a></p>
<p class="small">
Code and content © 2011–2014 <a href="/" title="Reliable Exchange Rate API, JSONP and HTTPS support">openexchangerates.org</a>.
All usage of Open Exchange Rates website, API and services are subject to the <a href="/terms" title="Terms & Conditions">Terms & Conditions</a> and <a href="/privacy" title="Privacy Policy">Privacy Policy</a>.
</p>
thanks again,
nico
</div>
</footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="/js/libs/prettify/prettify.js"></script>
<script src="/js/mailcheck.min.js"></script>
<script src="/js/libs/accounting.min.js"></script>
<script src="/js/libs/money.min.js"></script>
<script type="text/javascript">fx.base="USD";fx.rates={};$('[data-v]').each(function(){fx.rates[$(this).text().toUpperCase().trim()]=$(this).data('v')})</script>
<script src="/js/main.js"></script>
<script src="/js/bootstrap-popover-tooltip.min.js"></script>
<script type="text/javascript">
$('.more').popover({
placement: 'top',
trigger: 'hover'
}).mouseout(function () {
$(this).popover('destroy').popover({
placement: 'top',
trigger: 'hover'
});
});
</script>
</body>
</html>
|
|
|
|
|
It took me a while to reply, busy day))
Anyway, the problem is that now Open Exchange Rates requires you to get a unique id (AppID, it's free) to access json data on the site, and url you request latest data from should be like this:
https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID
So, instead of json data for the rates, the whole front page of https://openexchangerates.org[^] is being downloaded because it redirects there, if no App Id is specified, and of course fails to parse.
To fix your problem:
1. Get your unique App Id here (on free plan): https://openexchangerates.org/signup/free[^]
2. Use extension in this article like this, but with the value of your new App Id (replace YOUR_APP_ID below):
var url = "https://openexchangerates.org/api/latest.json?app_id=YOUR_APP_ID";
var currencyRates = _download_serialized_json_data<CurrencyRates>(url);
Or see Open Exchange Rates documentation[^] for more details on how to access their API.
Hope that works for you!
Regards,
Mikhail
|
|
|
|
|
Thanks again Mikhail, It worked!
Ciao,
Nico
|
|
|
|
|
Message Closed
modified 18-Jul-13 8:30am.
|
|
|
|
|
|
thanks for above example
How can I do the reverse?
ie serialize .net class to Json object and send to a webservice
regards
Omage Femi
|
|
|
|
|
Hi,
What was changed on April 29 ?
It's always nice to know what content/code in the article was updated/edited/changed.
You wrote: "In fact, Json.Net became so popular, that it will be included as a integral part of .NET MVC4 framework." The link you give is now re-directed here: [^], but I don't find any reference to Json.Net in the content.
thanks, Bill
Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
modified 30-Apr-13 7:55am.
|
|
|
|
|
Hi Bill, I haven't changed anything on April 29th, it was one of the editors (I am not sure what they changed). I did update it today though to remove that line that you mentioned since I can't find that mention anymore either. They apparently used to have a mention of Json.Net on MVC4 roadmap page, but since MVC4 is out, they removed the roadmap.
Also I am not sure they actually added it in a same way the original library works, MVC has some processing for JSON (you can just return Json(...) as JsonResult from controller), but I am not sure it is related to Json.Net. I still prefer to use Json.Net just beacause it's stable and always works they way I need to.
|
|
|
|
|
Nice article! Just as a tip, in Visual Studio 2012 you can copy some JSON to the clipboard, go to 'Paste JSON as Classes' and it'll drop in the correct class definitions for you, sometimes a useful timesaver
|
|
|
|
|
+5
That's a great tip, Dave. I think many other people on CP who might not read this article, would enjoy knowing that. Perhaps post at Tip/Trick ?
thanks,Bill
Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
modified 4-May-17 8:30am.
|
|
|
|
|
Good idea! I'll post a tip when I get a chance, as it's quite a nice feature that until recently I didn't even know was there!
|
|
|
|
|
Nice tip, thanks Dave! I've updated this article to include this.
|
|
|
|
|
My pleasure - nice article!
|
|
|
|
|
fyi: using 'JSON Paste does not require a reference to the JSON.NET assembly. I mention this because I think some readers of your article may assume this.
cheers, Bill
«When I consider my brief span of life, swallowed up in an eternity before and after, the little space I fill, and even can see, engulfed in the infinite immensity of spaces of which I am ignorant, and which know me not, I am frightened, and am astonished at being here rather than there; for there is no reason why here rather than there, now rather than then.» Blaise Pascal
|
|
|
|
|
Hi,
Thanks for your great and practical article. as I have noticed this task is used as GET JSON level. would you provide a example, to use your logic for a POST JSON task.
Thanks,
|
|
|
|
|
Hi, I'm just trying to learn JSON and I'm starting with the JSON.net. Your example has been the closest I have found to help me so far, but I have a JSON return value that will be something more like:
{
"loginResponse": {
"Map": {
"contactId": 5,
"accountId": 33ZG3244,
"accountName": "Item1",
"firstName": "myname",
"lastName": "mylastname",
"readOnly": false,
"email": "my@email.com",
}
}
}
I've been able to read it to a JObject and can access the values using the [key] indexes, but I would like to just get this converted directly into a class object (or any other way if possible).
It's not an array but I haven't figured out an easy way to convert it. Is there anything you can help me with on this? I'm just starting to look over your procedure, but wasn't sure if that would work with the JSON layout I'm working with and then if it would, not sure what the class structure should look like for something like this.
Thank you for any information possible.
Mike...
|
|
|
|
|
Interesting case. Honestly, I didn't know how to do that at first, so I had to figure it out))
As a result, here is a simple WebForms app I created with a solution to your particular problem, It'll just map your Json to a regular nested class, just like you wanted:
https://dl.dropbox.com/u/37444966/JsonNetExample%20-%20Nested%20Class.zip[^]
Thanks for challenging me today! It's always good to learn something new
|
|
|
|
|
Thank you very much. That's exactly what I needed. I actually attempted that exact same thing once, but I finally found out that my problem was just in the deserializing of the json value itself so I never got back and reattempted this method again.
Thank you,
Mike...
|
|
|
|
|
I have a class and correspoding JSon with the following structure in Silverlight 5.0:
JSon data:
[{"UserId":1,"LoginId":"abc","FirstName":"Rupak Kumar","LastName":"Das","Roles":[{"UserRoleId":1,"UserRoleName":"ReadOnly"},{"UserRoleId":2,"UserRoleName":"Edit"}]}]
Class definition:
public class Users
{
#region Properties
public int UserId { get; set; }
public string LoginId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ObservableCollection<UserRoles> Roles { get; set; }
#endregion
}
public class UserRoles
{
#region Properties
public int UserRoleId { get; set; }
public string UserRoleName { get; set; }
#endregion
}
I want to convert the JSon data directly to populate the object of Users.
Please help!!
rhythm divine..
|
|
|
|
|
No problem!
Here you go:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public List<Users> MapUsers() {
var json_data = "[{\"UserId\":1,\"LoginId\":\"abc\",\"FirstName\":\"Rupak Kumar\",\"LastName\":\"Das\",\"Roles\":[{\"UserRoleId\":1,\"UserRoleName\":\"ReadOnly\"},{\"UserRoleId\":2,\"UserRoleName\":\"Edit\"}]}]";
List<Users> users = JsonConvert.DeserializeObject<List<Users>>(json_data);
return users;
}
This will return a list of you Json data mapped to your Users class. Just give it your source Json string instead of static variable, and you'll be good to go. I tested that in a sample project with the latest version of Json.Net library and it works great!
Good luck!
|
|
|
|
|
When I am trying to user the snippet provided by you, it gives the below error:
Quote: InvalidCastException: It is not possible to automatically convert a value of JSON type 'Array' to JSON type 'String'.
{System.InvalidCastException: It is not possible to automatically convert a value of JSON type 'Array' to JSON type 'String'.
at System.Json.JsonValue.CheckIfJsonType(JsonType valueType, JsonType targetType)
at System.Json.JsonValue.op_Implicit(JsonValue value)
at ExpenseTracker.ViewModels.LoginViewModel._ApiStub_GetUserDetailsServiceEvent(Object sender, CustomEventArgs`1 e)}
CustomEventArgs<object> => contains my jsondata as..
{[{"UserId":1,"LoginId":"abc","FirstName":"Rupak Kumar","LastName":"Das","Roles":[{"UserRoleId":1,"UserRoleName":"ReadOnly"},{"UserRoleId":2,"UserRoleName":"Edit"}]}]}
eJsonArray jsonData = (JsonArray)e.Value;
ObservableCollection<Users> users = JsonConvert.DeserializeObject<ObservableCollection<Users>>(jsonData);
So, I just converted the json data to string while passing to the DeserializeObject method. And BINGO!
BUT, I still have another small query and another observation. This method does not populate the values of static properties (I removed the static keyword and it populates the value). And also, what if, the properties that I am populating belong to a static class. For now, I am directly accessing the Values against the Keys for populating the static properties of the static class.
Kindly provide a logic to overcome the same or let me know if this is a limitation.
rhythm divine..
modified 7-Oct-12 16:34pm.
|
|
|
|
|
Great, that you got it at least partially working. Since I never worked with Silverlight, I might nto be able to help you with its specifics. We'll see.
As for not being able to map JSON to static class, this is not really a limitation. Static classes with static properties are designed to be used in a particular manner:
var variable = StaticClass.StaticProperty();
Static classes cannot be inherited or have an interface, be a part of a list or collection, etc. Their main purpose is to be called directly or as an extensions of another classes.
On the other hand non-static classes can have interfaces and be inherited, and inherit from. They provide more flexibility that static ones.
Both types have their own place in C# (.NET) ecosystem where particular usage is enforced.
To work with data retrieved from JSON you shouldn't need to use static class (unless it is a specific requirment of Silverlight, which again I am not familiar with).
If you really need to use static class, you'll most probably have to map your dynamic class by manually:
var user = new User { };
YourStaticUsersClass.UserId = user.UserId;
YourStaticUsersClass.LoginId = user.LoginId;
YourStaticUsersClass.FirstName = user.FirstName;
Once again you shouldn't be needing to explicitly use static class or properties, unless it is some requirement of Silverlight.
How is data retrieved from JSON should be used in your application? Can you give any sample code of how or where it is intended to be used?
|
|
|
|
|