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.
New to C# and JSON but basically I have to use a C# script component in SSIS to extract data from a web service. I was able to do it initially with a different JSON format but this one includes an array.
I get the following error:
"Type 'Rootobject' is not supported for deserialization of an array."
Below is how I call the Deserializer:
//Deserialize our JSON
JavaScriptSerializer sr = new
jsonResponse = sr.Deserialize<Rootobject>(responseFromServer);
Here is my JSON structure (not quite all since fairly large):
[
{
"status":"SUCCESS",
"object":{
"responseStatusCode":0,
"productId":"35100003",
"cansimId":"251-0008",
"cubeTitleEn":"Average counts of young persons in provincial and territorial correctional services",
"cubeTitleFr":"Comptes moyens des adolescents dans les services correctionnels provinciaux et territoriaux",
"cubeStartDate":"1997-01-01",
"cubeEndDate":"2017-01-01",
"frequencyCode":12,
"nbSeriesCube":174,
"nbDatapointsCube":3468,
"releaseTime":"2019-05-09T08:30",
"archiveStatusCode":"2",
"archiveStatusEn":"CURRENT - a cube available to the public and that is current",
"archiveStatusFr":"ACTIF - un cube qui est disponible au public et qui est toujours mise a jour",
"subjectCode":[
"350102",
"4211"
],
"surveyCode":[
"3313"
],
"dimension":[ ],
"footnote":[ ],
"correction":[
]
}
}
]
Finally here is my Class structure obtained through Paste Special in Visual Studio:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string status { get; set; }
public Object _object { get; set; }
}
public class Object
{
public int responseStatusCode { get; set; }
public string productId { get; set; }
public string cansimId { get; set; }
public string cubeTitleEn { get; set; }
public string cubeTitleFr { get; set; }
public string cubeStartDate { get; set; }
public string cubeEndDate { get; set; }
public int frequencyCode { get; set; }
public int nbSeriesCube { get; set; }
public int nbDatapointsCube { get; set; }
public string releaseTime { get; set; }
public string archiveStatusCode { get; set; }
public string archiveStatusEn { get; set; }
public string archiveStatusFr { get; set; }
public string[] subjectCode { get; set; }
public string[] surveyCode { get; set; }
public Dimension[] dimension { get; set; }
public Footnote[] footnote { get; set; }
public object[] correction { get; set; }
}
public class Dimension
{
public int dimensionPositionId { get; set; }
public string dimensionNameEn { get; set; }
public string dimensionNameFr { get; set; }
public bool hasUom { get; set; }
public Member[] member { get; set; }
}
public class Member
{
public int memberId { get; set; }
public int? parentMemberId { get; set; }
public string memberNameEn { get; set; }
public string memberNameFr { get; set; }
public string classificationCode { get; set; }
public string classificationTypeCode { get; set; }
public int? geoLevel { get; set; }
public int? vintage { get; set; }
public int terminated { get; set; }
public int? memberUomCode { get; set; }
}
public class Footnote
{
public int footnoteId { get; set; }
public string footnotesEn { get; set; }
public string footnotesFr { get; set; }
public Link link { get; set; }
}
public class Link
{
public int footnoteId { get; set; }
public int dimensionPositionId { get; set; }
public int memberId { get; set; }
}
I know the problem lies within how I call the Deserialize<Rootobject> and different data types but I wasn't able to find the solution. Any suggestions are appreciated.
AV
Try deserializing directly to a list of Class1.
jsonResponse = sr.Deserialize<List<Class1>>(responseFromServer);
Also, don't use Object as your class name. That's a really bad practice.
You can control how JSON.NET serializes/deserializes a property as shown here: How can I change property names when serializing with Json.net?
e.g.
[JsonProperty(PropertyName = "object")]
public class MyObject
{
}
I'm trying to Deserialize some json using JsonConver.DeserializeObject. however it's not working on some json from the api I'm using. here is a link that does not work: https://api.pokemontcg.io/v1/cards?setCode=smp
and here is a link that does work. https://api.pokemontcg.io/v1/cards?setCode=sm2
I'm not sure why it sometimes works and sometimes not. The data that comes out of it is very similar to each other, just different cards.
Here is the code:
public static async Task<T> GetDataAsync<T>(this HttpClient client, string address, string querystring)
where T : class
{
var uri = address;
if (!string.IsNullOrEmpty(querystring))
{
uri += querystring;
}
var httpMessage = await client.GetStringAsync(uri);
var jsonObject = JsonConvert.DeserializeObject<T>(httpMessage);
return jsonObject;
}
Now my card class
namespace CardAppReal.Lib.Models
{
public class Card
{
public string id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string supertype { get; set; } // if pokemon, trainer or energy
public string setcode { get; set; }
public int number { get; set; }
public string set { get; set; }
}
}
With a root
using System.Collections.Generic;
using CardAppReal.Lib.Models;
namespace CardAppReal.Lib.Entities
{
public class RootCard
{
public List<Card> cards { get; set; }
}
}
If u could help me out I would find it amazing.
I have tested your json.
this is the Model
namespace Test
{
public class Attack
{
public List<string> cost { get; set; }
public string name { get; set; }
public string text { get; set; }
public string damage { get; set; }
public int convertedEnergyCost { get; set; }
}
public class Weakness
{
public string type { get; set; }
public string value { get; set; }
}
public class Resistance
{
public string type { get; set; }
public string value { get; set; }
}
public class Ability
{
public string name { get; set; }
public string text { get; set; }
public string type { get; set; }
}
public class Card
{
public string id { get; set; }
public string name { get; set; }
public int nationalPokedexNumber { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string subtype { get; set; }
public string supertype { get; set; }
public string hp { get; set; }
public List<string> retreatCost { get; set; }
public string number { get; set; }
public string artist { get; set; }
public string rarity { get; set; }
public string series { get; set; }
public string set { get; set; }
public string setCode { get; set; }
public List<string> types { get; set; }
public List<Attack> attacks { get; set; }
public List<Weakness> weaknesses { get; set; }
public List<Resistance> resistances { get; set; }
public string evolvesFrom { get; set; }
public Ability ability { get; set; }
public List<string> text { get; set; }
}
public class RootObject
{
public List<Card> cards { get; set; }
}
}
And this is how I call the Deserialize
RootObject root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(RootObject.WRONG_JSON);
(NB WRONG_JSON is your json string...)
I'm programming a C# implementation for the Qualtrics API (v 2.5) using RestSharp. When calling the method getUserIds, it returns a list of users in JSON format (see the example output below).
The problem/question I face is that for each user object (the list of objects under Result) it generates a different id, starting with URH_. When using json2csharp it assumes ofcourse that it's always a different class, while in fact it's absolutely the same one as you can see in the output, and as is stated in the documentation of the api. How can I best resolve this - so that I can make a class UserData that I can reuse? Because now I obviously always see these random URH_ prefixed classes in each response.
NOTE: I was thinking I could try to massage the response first, and when I get the response replace each URH_ prefixed object under the root Result object with a "UserData" string - but I feel this is breaking the rules a bit, and thought the community would have a better solution?
Below is the raw JSON output (note that I removed sensitive information):
{"Meta":{"Status":"Success","Debug":""},"Result":{"URH_3wpA9pxGbE0c7Xu":{"DivisionID":null,"UserName":"user.name#domain.com","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_4SjjZmbPphZGKDq","UserEmail":"x.x#x.x","UserAccountStatus":"Active"},"URH_57vQr8MVXgpcPUo":{"DivisionID":"DV_XXXXXXXX","UserName":"jxxxx#xx.xxx","UserFirstName":"X","UserLastName":"X","UserAccountType":"UT_BRANDADMIN","UserEmail":"xxxx#xxg.xxx","UserAccountStatus":"Active"},"URH_6ujW1EP0QJOUaoI":{"DivisionID":"DV_XXXXXXXYZ","UserName":"x.xckx#xxx.xyz","UserFirstName":"x","UserLastName":"x","UserAccountType":"UT_XXXXXABCD","UserEmail":"c.c#cc.com","UserAccountStatus":"Active"}}}
This is what I get when generating a model using json2csharp:
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class URH3wpA9pxGbE0c7Xu
{
public object DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH57vQr8MVXgpcPUo
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class URH6ujW1EP0QJOUaoI
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}
public class Result
{
public URH3wpA9pxGbE0c7Xu URH_3wpA9pxGbE0c7Xu { get; set; }
public URH57vQr8MVXgpcPUo URH_57vQr8MVXgpcPUo { get; set; }
public URH6ujW1EP0QJOUaoI URH_6ujW1EP0QJOUaoI { get; set; }
}
public class RootObject
{
public Meta Meta { get; set; }
public Result Result { get; set; }
}
It's simple - just use Dictionary<string, UserData> generic type for Result field:
public class Response
{
public Meta Meta { get; set; }
public Dictionary<string, UserData> Result { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Debug { get; set; }
}
public class UserData
{
public string DivisionID { get; set; }
public string UserName { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserAccountType { get; set; }
public string UserEmail { get; set; }
public string UserAccountStatus { get; set; }
}