I have an issue with deserializing the JSON file from the web to a List.
My code is down below, but it does not execute and shows Newtonsoft.Json.JsonSerializationException.
static void Main(string[] args)
{
List<Root> coinDatas = new List<Root>(); ;
callApi(coinDatas);
Console.ReadKey();
}
private static async void callApi(List<Root> coinDatas)
{
string url = "https://api.coinstats.app/public/v1/coins?skip=0&limit=50¤cy=USD";
HttpClient httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(url);
string jsonResponse = await httpResponse.Content.ReadAsStringAsync();
coinDatas = JsonConvert.DeserializeObject<List<Root>>(jsonResponse);
}
public class Coin
{
public string id { get; set; }
public string icon { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public int rank { get; set; }
public double price { get; set; }
public double priceBtc { get; set; }
public double volume { get; set; }
public double marketCap { get; set; }
public double availableSupply { get; set; }
public double totalSupply { get; set; }
public double priceChange1h { get; set; }
public double priceChange1d { get; set; }
public double priceChange1w { get; set; }
public string contractAddress { get; set; }
public int? decimals { get; set; }
}
public class Root
{
public List<Coin> coins { get; set; }
}
I've donloaded JSON from your url. It looks like this:
{
"coins": [
{
"id": "bitcoin",
"icon": "https://static.coinstats.app/coins/1650455588819.png",
"name": "Bitcoin",
"symbol": "BTC",
"rank": 1,
"price": 16591.950104477022,
"priceBtc": 1,
"volume": 9476109498.476653,
"marketCap": 319384453847.01608,
"availableSupply": 19249362,
"totalSupply": 21000000,
"priceChange1h": 0.15,
"priceChange1d": 0.05,
"priceChange1w": -1.21,
"websiteUrl": "http://www.bitcoin.org",
"twitterUrl": "https://twitter.com/bitcoin",
"exp": [
"https://blockchair.com/bitcoin/",
"https://btc.com/",
"https://btc.tokenview.io/"
]
}
]
}
I suppose ytour problem in coinDatas = JsonConvert.DeserializeObject<List<Root>>(jsonResponse); line.
You have only one root element, lit a list of them.
And, by the way, your code does not return any value.
I recommend you to rwerite your method to somewthing like this:
private static async Task<Root> callApiAsync()
{
string url = "https://api.coinstats.app/public/v1/coins?skip=0&limit=50¤cy=USD";
HttpClient httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(url);
string jsonResponse = await httpResponse.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Root>(jsonResponse);
}
then you can use this method in Main (notice async word in this method too):
static async void Main(string[] args)
{
var coinDatas = await callApiAsync();
Console.ReadKey();
}
if you just need a list of coins, you can change the code to this
async Task Main()
{
List<Coin> coins = await callApiAsync();
Console.ReadLine();
}
static async Task<List<Coin>> callApiAsync()
{
string url = "https://api.coinstats.app/public/v1/coins?skip=0&limit=50¤cy=USD";
// your another code
var data= JsonConvert.DeserializeObject<Root>(jsonResponse);
return data.coins;
}
Related
I am trying to read and write a value on appsettings.json.It is called Refreshed_Token. I have found something on internet and it was very well explained as an example but i get only one error. Can you please guys help me thank you very much.
Worker.cs
public async Task request_refresh_token()
{
var client = new RestClient("https://accounts.zoho.eu/oauth/v2/token?grant_type=authorization_code&client_id=" +_config.Value.Zoho_Client_Id+ "&client_secret=" +_config.Value.Zoho_Client_Secret+ "&code=" +_config.Value.Zoho_Code);
var request = new RestRequest();
request.AddHeader("Cookie", "xxx; xxx; iamcsr=xxx");
RestResponse response = await client.PostAsync(request);
var result = JObject.Parse(response.Content);
var refresh_token = result["refresh_token"].Value<string>();
update_appsettings_json(refresh_token);
}
public void update_appsettings_json(string refresh_token)
{
var appSettingsPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "appsettings.json");
var json = File.ReadAllText(appSettingsPath);
var jsonSettings = new JsonSerializerSettings();
jsonSettings.Converters.Add(new ExpandoObjectConverter());
jsonSettings.Converters.Add(new StringEnumConverter());
dynamic config = JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(json, jsonSettings);
config.Config.Zoho_Code = Zoho_Refreshed_Token.refresh_token;
var newJson = JsonConvert.SerializeObject(config, Formatting.Indented, jsonSettings);
File.WriteAllText(appSettingsPath, newJson);
}
appsetting.json file :
{
"Config": {
"LeadCustomerId": "4096",
"URL": "example.com",
"Token": "xxx",
"Contact_Custom_Id": "11249",
"Opportunity_Custom_Id": "11261",
"Account_Custom_Id": "13397",
"Task_Custom_Id": "16876",
"Call_Custom_Id": "17033",
"Meeting_Custom_Id": "17098",
"Zoho_Client_Id": "xxx",
"Zoho_Client_Secret": "xxx",
"Zoho_Code": "xxx",
"Zoho_Refreshed_Token": ""
}
}
Config.cd file is:
public class Config
{
public string LeadCustomerId { get; set; }
public string WeclappURL { get; set; }
public string Weclapp_Token { get; set; }
public string Contact_Custom_Id { get; set; }
public string Opportunity_Custom_Id { get; set; }
public string Account_Custom_Id { get; set; }
public string Task_Custom_Id { get; set; }
public string Call_Custom_Id { get; set; }
public string Meeting_Custom_Id { get; set; }
public string Zoho_Client_Id { get; set; }
public string Zoho_Client_Secret { get; set; }
public string Zoho_Code { get; set; }
public string Zoho_Refreshed_Token { get; set; }
}
The error i get is this: The Zoho_Refreshed_Token does not exist in the current context
Thank you for your time!
Im trying to parse JSON into ListView, but its giving me deserialization error.
This is my model - it's same as api's keys:
public class Currency
{
public string Drzava { get; set; }
public int Sifra_valute { get; set; }
public string Drzava_iso { get; set; }
public int Jedinica { get; set; }
public double Kupovni_tecaj { get; set; }
public double Srednji_tecaj { get; set; }
public double Prodajni_tecaj { get; set; }
}
This is my list of Currencies:
public class CurrencyTable
{
public List<Currency> Results { get; set; }
}
Class for binding with Listview:
public class ShowCurrency
{
static ShowCurrency() {
using (var webClient = new WebClient())
{
String rawJSON =
webClient.DownloadString("http://api.hnb.hr/tecajn/v2/");
CurrencyTable currencyTable =
JsonConvert.DeserializeObject<CurrencyTable>(rawJSON);
}
}
private static List<Currency> currencies;
public static List<Currency> Currencies { get; set; }
public static List<Currency> GetCurrencies() {
return Currencies;
}
}
And i get error at: CurrencyTable currencyTable =
JsonConvert.DeserializeObject(rawJSON);
this is how api looks like:
http://api.hnb.hr/tecajn/v2
The web-service response body starts with this text:
[{"broj_tecajnice":"85","datum_primjene":"2019-05-...
Note how it starts with [ which means it's returning a JSON array directly as its root object and that it is not returning an object with a member named Results (i.e. it is not returning { Results: [ {"broj_tecajnice"... }, { ... } ] }.
Change your code to this:
List<Currency> list = JsonConvert.DeserializeObject<List<Currency>>( rawJSON );
CurrencyTable currencyTable = new CurrencyTable()
{
Results = list
};
I started to learn C# and some Json, I am trying to get this form of Json format:
Desired Output :
I have tried this:
static void Main(string[] args)
{
var myjason = new myJson
{
ContentDisposition = "",
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
features = new[] { "te" },
te = new te { reports = new[] { "pdf", "xml" } },
// images = new img { { a.id = "7e6fe36e-889e-4c25-8704-56378f0830df", a.revision = 1 }, { a.id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", a.revision = 1 } }
};
string json = JsonConvert.SerializeObject(myjason, Formatting.Indented);
Console.WriteLine(json);
}
public class myJson
{
public string ContentDisposition{ get; set; }
public string md5 { get; set; }
public string file_name { get; set; }
public string[] features { get; set; }
public te te { get; set; }
public img images { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
}
public class img
{
public a[] images { get; set; }
}
And here is my current output:
Current output:
Please help, thanks a lot!
I think you are a bit confused about what's going on here. It looks like you're trying to POST some JSON to some endpoint.
Content-Disposition and Content-Type are HTTP headers. They are not JSON.
The JSON starts with the first { and this is the body of the POST. To create that body, you could use a C# object like:
public class MyJson {
public class MyRequest request {get ;set;}
}
public class MyRequest {
public string md5 {get;set;}
public string file_name {get;set;}
public string file_type {get;set;}
public List<string> features {get;set;}
public MyTe te {get;set;}
}
public class MyTe {
public List<string> reports {get;set;}
public List<MyImages> images {get;set;}
}
public class MyImages {
public string id {get;set;}
public int revision {get;set;}
}
And then use JsonConvert.SerializeObject on a MyJson object. To set the HTTP headers depends on what you're trying to do and with which tools, and that probably belongs in a different question.
EDIT: I said "and so on" because it's really just a rote exercise, and there are better tools to do this but I've updated.
Content-Disposition and Content-Type are request headers so they don't need to be in your json body
Here I've also demostrated how you can set a custom json property name using JsonProperty attribute.
static void Main(string[] args)
{
var myjason = new myJsonClass
{
Request = new requestClass
{
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
file_type = "docx",
features = new[] { "te" },
te = new te
{
reports = new[] { "pdf", "xml" },
images = new a[] { new a { id = "7e6fe36e-889e-4c25-8704-56378f0830df", revision = 1 }, new a { id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", revision = 1 } }
},
}
};
string json = JsonConvert.SerializeObject(myjason, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class myJsonClass
{
[JsonProperty("request")]
public requestClass Request { get; set; }
}
public class requestClass
{
public string md5 { get; set; }
public string file_name { get; set; }
public string file_type { get; set; }
public string[] features { get; set; }
public te te { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
public a[] images { get; set; }
}
Output:
{
"request": {
"md5": "da855ff838250f45d528a5a05692f14e",
"file_name": "MyFile.docx",
"file_type": "docx",
"features": [
"te"
],
"te": {
"reports": [
"pdf",
"xml"
],
"images": [
{
"id": "7e6fe36e-889e-4c25-8704-56378f0830df",
"revision": 1
},
{
"id": "e50e99f3-5963-4573-af9e-e3f4750b55e2",
"revision": 1
}
]
}
}
}
Trying to get JSON data from ThingSpeak however getting the above error,
works well with JSON placeholder as the URL.
Here is my main cs code:
namespace Drip
{
public class Feed
{
public DateTime Created_at { get; set; }
public int Entry_id { get; set; }
public string Field1 { get; set; }
}
public partial class DripPage : TabbedPage
{
private const string Url = "https://thingspeak.com/channels/301726/field/1.json";
private HttpClient _client = new HttpClient();
private ObservableCollection<Feed> _data;
public DripPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
var content = await _client.GetStringAsync(Url);
var data = JsonConvert.DeserializeObject<List<Feed>>(content);
_data = new ObservableCollection<Feed>(data);
postsListView.ItemsSource = _data;
base.OnAppearing();
}
Here is my JSON:
{
"channel": {
"id": 301726,
"name": "Testing ESP8266",
"description": "Water meter pulse count",
"latitude": "0.0",
"longitude": "0.0",
"field1": "Water Pulse",
"created_at": "2017-07-12T12:19:38Z",
"updated_at": "2017-09-26T08:41:17Z",
"elevation": "54",
"last_entry_id": 151
},
"feeds": [
{
"created_at": "2017-08-15T13:14:28Z",
"entry_id": 52,
"field1": "13.00\r\n\r\n"
},
{
"created_at": "2017-08-15T13:14:44Z",
"entry_id": 53,
"field1": "13.00\r\n\r\n"
},
{
"created_at": "2017-08-15T13:14:59Z",
"entry_id": 54,
"field1": "13.00\r\n\r\n"
}
]
}
The returned json is not an array, so it can't be deserialized as a List<Feed>, hence an exception is thrown. It is an object, and one of that object's members is the array that you are interested in. The backing C# class to deserialize should have the following members:
public class RootObject
{
public Channel channel { get; set; }
public List<Feed> feeds { get; set; }
}
public class Channel
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string field1 { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string elevation { get; set; }
public int last_entry_id { get; set; }
}
public class Feed
{
public DateTime created_at { get; set; }
public int entry_id { get; set; }
public string field1 { get; set; }
}
Instead of deserializing to a List<Feed>, you would deserialize to a RootObject (or whatever you choose to call it):
var data = JsonConvert.DeserializeObject<RootObject>(content);
_data = new ObservableCollection<Feed>(data.feeds);
try this maybe it will work fine for you
first: place this code on your activity and instanciate all var;you will create a javalist to deserialize your json, then you will the method webclient to get your json, then you will use the method runonuithread to excute the process in background.
articles = new JavaList<RootObject>();
mWebClient = new WebClient();
mUrl = new Uri(urlAddress);
mWebClient.DownloadDataAsync("https://thingspeak.com/channels/301726/field/1.json");
mWebClient.DownloadDataCompleted += MWebClient_DownloadDataCompleted;
second: the method mWebClient.DownloadDataCompleted will generate this :
private void MWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
RunOnUiThread(() =>
{
try
{
string json = Encoding.UTF8.GetString(e.Result);
articles = JsonConvert.DeserializeObject<JavaList<RootObject>>(json);
mAdapter = new ArticleAdapterCostum(this, articles);
mListView.Adapter = mAdapter;
}
catch (Exception exception)
{
Toast.MakeText(this, " Vueillez verifier votre connexion a internet puis reessayer ", ToastLength.Short).Show();
}
});
}
don't forget to create a costum adapter to your listview.
I'm trying to replicate the functionality in one of MoshHamedani's course on Xamarin Forms.
Here's my code (with a valid, working _url, that returns a json object with escape characters):
public partial class PartnersListPage : ContentPage
{
private const string _url = "xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz";
private HttpClient _httpClient = new HttpClient();
private ObservableCollection<Partner> _partners;
public PartnersListPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
var jsonObject = await _httpClient.GetStringAsync(_url);
var dotNetObject = JsonConvert.DeserializeObject<List<Partner>>(jsonObject);
_partners = new ObservableCollection<Partner>(dotNetObject);
partnersListView.ItemsSource = _partners;
base.OnAppearing();
}
Partner.cs looks like this:
public class Partner
{
//public int Id { get; set; }
//public string Name { get; set; }
public string ImageUrl { get; set; }
public string WebUrl { get; set; }
}
Postman returns the following:
{
"partners": [
{
"imageUrl": "http://www.abcdefgh.xy//media/1007/3.jpg",
"webUrl": "http://www.abcdefgh.xy/"
},
{
"imageUrl": "http://www.ijklmnop.xy//media/1009/5.jpg",
"webUrl": "https://www.ijklmnop.xy/xy"
},
{
"imageUrl": "http://www.qrstuvxy.xy//media/2623/slsp.svg",
"webUrl": "https://www.qrstuvxy.xy/"
}
]
}
When I hit the JsonConvert.DeserializeObject line, I get the following:
An unhandled exception occured. Why is it not working?
You are deserializing with incorrect type (List<Partner>)
I'm using Json to c# converter in order to determine the class I need - just paste in your json text/data and in will generate the classes for you. For the example for your json text/data you need:
public class Partner
{
public string imageUrl { get; set; }
public string webUrl { get; set; }
}
public class RootObject
{
public List<Partner> partners { get; set; }
}
........
var result = JsonConvert.DeserializeObject<RootObject>(jsonObject);
controller returning single object but you are trying to array deserialize
public class Partner
{
//public int Id { get; set; }
//public string Name { get; set; }
public string ImageUrl { get; set; }
public string WebUrl { get; set; }
}
public class ApiResult
{
List<Partner> Partners {get;set;}
}
and..
var dotNetObject = JsonConvert.DeserializeObject<ApiResult>(jsonObject);