Why my deserialization is giving me an error Newtonsoft.Json.JsonConvert? - c#

public List<CoinMarket> GetCoinMarket()
{
List<CoinMarket> coinMarket = new List<CoinMarket>();
var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get";
try
{
using (var Client = new System.Net.Http.HttpClient())
{
var JSON = Client.GetStringAsync(URLWebAPI);
coinMarket = (List<CoinMarket>)Newtonsoft.Json.JsonConvert.DeserializeObject(JSON.Result);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#" ERROR {0}", ex.Message);
}
return coinMarket;
}
It is throwing and i do not know why. It looks like there is something wrong with the serialization part. But i verified it.

You are using json deserializer incorrectly. DeserializeObject returns custom object which is not castable to your List<T>. This output:
Newtonsoft.Json.Linq.JArray
SO20171129.CoinData[]
System.Collections.Generic.List`1[SO20171129.CoinData]
is the result of this code.
class Program
{
static void Main(string[] args)
{
// returns Newtonsoft.Json.Linq.JArray
var coinMarket = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText("get.json"));
Console.WriteLine(coinMarket.GetType());
// returns array of CoinData
var coinMarketTyped = Newtonsoft.Json.JsonConvert.DeserializeObject<CoinData[]>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped.GetType());
// returns List of CoinData
var coinMarketTyped2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CoinData>>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped2.GetType());
}
}
public class CoinData
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
public string __invalid_name__24h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}

My guess is that your json structure members do not match the CoinMarket class members.
What I would do is to copy the json result and generate the corresponding CoinMarket class on the following website: http://json2csharp.com/
It will output the right CoinMarket class for you.

public class CoinMarket
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
[JsonProperty("24h_volume_usd")]
public string h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
}
This is my CoinMarket Class

Related

Newtonsoft Json Convert does not convert json string to object

I have these classes
public class ResponseEntryInfoAndTollDue
{
public int Code { get; set; }
public string Message { get; set; }
public TagEntryInfo TagEntryInfo { get; set; }
public TollMatrix TollMatrix { get; set; }
public List<TagInfoParam> TagInfoParams { get; set; }
public ResponseEntryInfoAndTollDue()
{
TagEntryInfo = new TagEntryInfo();
TollMatrix = new TollMatrix();
TagInfoParams = new List<TagInfoParam>();
}
}
public class TagEntryInfo
{
public long TrxnID { get; set; }
public string TagRFIDNumber { get; set; }
public string EntryTrxnDTime { get; set; }
public int EntryPlaza { get; set; }
public short EntryLane { get; set; }
public string EntryDirection { get; set; }
public string EntryLaneType { get; set; }
public string PostingDateTime { get; set; }
public string Action { get; set; }
}
public class TollMatrix
{
public decimal TollDue { get; set; }
public decimal TollVat { get; set; }
public decimal TollNoVat { get; set; }
public bool IsDefaulted { get; set; }
}
public class TagInfoParam
{
public DateTime? AsOfDate { get; set; }
public Decimal? AvailableBalance { get; set; }
public string TagNumber { get; set; }
public string PLateNumber { get; set; }
public Int16 HonorPlate { get; set; }
public Int16 TagStatusID { get; set; }
public string TID { get; set; }
public string EPC { get; set; }
public string AccountTypeID { get; set; }
public Int16 AccountStatusID { get; set; }
public Int16 TagClassID { get; set; }
public Int16 Status { get; set; }
}
From a webservice I get this json string:
{"Result":{"Code":0,"Message":"With entry info computed toll due","TagEntryInfo":{"TrxnID":6666750,"TagRFIDNumber":"1234567890","EntryTrxnDTime":"2021-01-16 16:40:16.560","EntryPlaza":123,"EntryLane":1,"EntryDirection":"B","EntryLaneType":"A","PostingDateTime":"2021-01-16T16:43:16.05","Action":"A"},"TollMatrix":{"TollDue":164.0000,"TollVat":17.5700,"TollNoVat":146.4300,"IsDefaulted":false},"TagInfoParams":[{"AsOfDate":"2021-01-16T17:12:04.213","AvailableBalance":537.0000,"TagNumber":"1234567890","PLateNumber":"Q123","HonorPlate":1,"TagStatusID":1,"TID":"Elfkajs98","EPC":"889080990709","AccountTypeID":"REV","AccountStatusID":1,"TagClassID":1,"Status":1}]},"Id":351,"Exception":null,"Status":5,"IsCanceled":false,"IsCompleted":true,"CreationOptions":0,"AsyncState":null,"IsFaulted":false}
This is how I convert it:
var response = JsonConvert.DeserializeObject(ret);
I know that it doesn't get converted because this is what I get:
This is the result:
Why is this not being converted into an object?
As Fabio also mentioned that your json contains the attribute Result which is not part of your object so you can use below logic to deserialize
var jObj = JObject.Parse(json);
var responseEntryInfoAndTollDue = JsonConvert.DeserializeObject<ResponseEntryInfoAndTollDue>(jObj["Result"].ToString());
The above code first parse the Json to JObject and uses Result property to deserialize to ResponseEntryInfoAndTollDue object.
Check this fiddle - https://dotnetfiddle.net/7Pc3sJ

Problem trying to deserialize a json with a model

I am trying to deserialize a json (using Newtonsoft.Json), i created the classes, but in json code there is a variable that i don't know if it is corrected or i don't know how to deserialize.
I am getting a null exception on line : MessageBox.Show(root.matriculations._14000.name)
private void btnImportaDados_Click(object sender, EventArgs e)
{
string getDataUrl = "https://xxx.xxx.com/api/matriculations/get.json?entity_code=14000";
try
{
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(getDataUrl);
var root = JsonConvert.DeserializeObject<Rootobject>(json);
MessageBox.Show(root.matriculations._14000.name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public class Rootobject
{
public Matriculations matriculations { get; set; }
}
public class Matriculations
{
public _14000 _14000 { get; set; }
}
public class _14000
{
public string entity_code { get; set; }
public string name { get; set; }
public string street { get; set; }
public string local { get; set; }
public string postal_code { get; set; }
public string sub_postal_code { get; set; }
public string phone1 { get; set; }
public object phone2 { get; set; }
public string email1 { get; set; }
public object email2 { get; set; }
public string entity_code_2 { get; set; }
public string courseaction_ref { get; set; }
public string courseaction_id { get; set; }
public string course_code { get; set; }
public string course { get; set; }
public Billingorderplan[] billingorderplans { get; set; }
}
public class Billingorderplan
{
public string id { get; set; }
public string paid { get; set; }
public string date { get; set; }
public object obs { get; set; }
public object payment_doc_num { get; set; }
public string value { get; set; }
public string description { get; set; }
public string entity_code { get; set; }
public object paid_date { get; set; }
}
The result(json data) from the url is:
{"matriculations":{"14000":{"entity_code":"14000","name":"Fabio Danilson Sivone Antonio","street":"Rua Dr. Pereira Jardim, Bl. 3 - 25 - 4 B","local":"Luanda","postal_code":"2685","sub_postal_code":"093","phone1":"923810539","phone2":null,"email1":"fabiodanilson1#hotmail.com","email2":null,"entity_code_2":"9957","courseaction_ref":"EPCE_01","courseaction_id":"1828","course_code":"EPCE","course":"Especializa\u00e7\u00e3o Avan\u00e7ada em Investiga\u00e7\u00e3o de Crime Econ\u00f3mico [E-learning]","billingorderplans":[{"id":"298","paid":"0","date":"2020-05-06","obs":null,"payment_doc_num":null,"value":"0.00","description":"Inscri\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"299","paid":"0","date":"2019-11-21","obs":null,"payment_doc_num":null,"value":"0.00","description":"1\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"300","paid":"0","date":"2019-12-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"2\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"301","paid":"0","date":"2020-01-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"3\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"302","paid":"0","date":"2020-02-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"4\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"303","paid":"0","date":"2020-03-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"5\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"304","paid":"0","date":"2020-04-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"6\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"305","paid":"0","date":"2020-05-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"7\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"306","paid":"0","date":"2020-06-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"8\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"16595","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16596","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16597","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16598","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16599","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16601","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16600","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null}]}}}
But that "14000" is a varible value depending from the parameter passed.
How can i do it?
Thank You.
Since 14000 cannot be a variable name you will have to resort to some manual intervention to capture that dynamic value. The cleanest way is to remove the Matriculations class and replace it with Dictionary<int, _14000> (or Dictionary<string, _14000>).
public class Rootobject
{
public Dictionary<int, _14000> matriculations { get; set; }
}
This will ensure that the key is captured correctly even if it is a number. You can read the object from the dictionary's values as such: root.matriculations.Values.First().name. (Remember to import System.Linq for using .First().)
For clarity you can rename _14000 to something more descriptive.
You do not have _14000 in returned JSON but 14000 under matriculations.

Getting a JsonSerializationException when trying to deserialize PlayerStats

I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"

Deserializing the JSON Objest results in all null fields C#

My jsonResponse is something like this:
{"status":200,"data":{"first_name":"\u062e\u0633","last_name":"\u0635\u062f\u0627","national_code":"1","image_photo":"1.jpg","cellphone":"1234","city":{"id":1,"name":"x","created_at":"2017-02-27 17:54:44","updated_at":"2017-02-27 17:54:44"},"email":"something#gmail.com","even_odd":1,"Register Time":"2018-01-25 10:39:17","is_blocked":false,"receive_regular_offer":"false","level":1,"ride_count":0,"service_type":1,"bank":"\u0645","iban":"xy","card_number":"","holder":"\u062e\u0633","plate_number":"123","vehicle_model":"\u067e\u0698","vehicle_color":"\u062a\u0627\u06a9\u0633","unique_id":592875}}
I have created a class like this:
public class Driver
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public string city { get; set; }
public string email { get; set; }
public string even_odd { get; set; }
public bool is_blocked { get; set; }
public bool receive_regular_offer { get; set; }
public string level { get; set; }
public string ride_count { get; set; }
public string service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public string unique_id { get; set; }
}
and used this:
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Driver snappDriver = js.Deserialize<Driver>(jsonResponse);
But the result is all null!
1.your class should be defined right
example:
void Main()
{
var json =api();
//dynamic
var dynamic_json = JsonConvert.DeserializeObject(json).Dump() as JObject;
//strong type
var strong_Type_json = JsonConvert.DeserializeObject<Driver>(json).Dump() ;
}
string api(){
return #"
{""status"":200,""data"":{""first_name"":""\u062e\u0633"",""last_name"":""\u0635\u062f\u0627"",""national_code"":""1"",""image_photo"":""1.jpg"",""cellphone"":""1234"",""city"":{""id"":1,""name"":""x"",""created_at"":""2017-02-27 17:54:44"",""updated_at"":""2017-02-27 17:54:44""},""email"":""something#gmail.com"",""even_odd"":1,""Register_Time"":""2018-01-25 10:39:17"",""is_blocked"":false,""receive_regular_offer"":""false"",""level"":1,""ride_count"":0,""service_type"":1,""bank"":""\u0645"",""iban"":""xy"",""card_number"":"""",""holder"":""\u062e\u0633"",""plate_number"":""123"",""vehicle_model"":""\u067e\u0698"",""vehicle_color"":""\u062a\u0627\u06a9\u0633"",""unique_id"":592875}}
";
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class Data
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public City city { get; set; }
public string email { get; set; }
public int even_odd { get; set; }
public string Register_Time { get; set; }
public bool is_blocked { get; set; }
public string receive_regular_offer { get; set; }
public int level { get; set; }
public int ride_count { get; set; }
public int service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string plate_number { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public int unique_id { get; set; }
}
public class Driver
{
public int status { get; set; }
public Data data { get; set; }
}
2.json's key Register Time in strong type is invalid name
you can add _ in your json string to solve the problem
Try to create exactly the same class definition as your json has. Your Driver class describes json object's data property.
public class DriverWrapper
{
public string status { get; set; }
public Driver data { get; set; }
}
You have to create another object class that handles status and data property
try this
Create a class Response
class Response{
public int status { get; set;}
public Driver data { get; set;}
}
and do it this way
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Response snappDriver = js.Deserialize<Response>(jsonResponse);

LDAP SearchResponse to Json C#

I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }

Categories

Resources