NewtonSoft incorrect deserialization - c#

This is what I'm trying to deserialize.
I let Visual Studio generate these classes for deserialization.
But whenever I deserialize this data, I end up with the _56787 set being null. Here's the re-serialized data.
using (var client = new WebClient())
{
string temp = client.DownloadString($"https://api.frankerfacez.com/v1/room/leonardvdj");
Rootobject FFZEmotes = JsonConvert.DeserializeObject<Rootobject>(temp);
Console.WriteLine(JsonConvert.SerializeObject(FFZEmotes));
}
This is the code I use to retrieve the JSON. I've checked "temp"s value, and it download's correctly.
Anyone have any idea why this is happening?

You need to make sets into a dictionary instead of a type and rename _56787 to something more sensible:
public class Rootobject
{
public Room room { get; set; }
public Dictionary<string, Set> sets { get; set; }
}
public class Set
{
public int _type { get; set; }
public object css { get; set; }
public object description { get; set; }
public Emoticon[] emoticons { get; set; }
public object icon { get; set; }
public int id { get; set; }
public string title { get; set; }
}

Related

nested json deserialization - need another set of eyes

I have been trying to get this json to deserialize for two days now using RestSharp. I have gone through the RestSharp github site, looked at countless examples, and spent much time here on Stack Overflow to try and find the answer to no avail. My code had previously worked perfectly but the vendor changed their API version and I was forced to do an update to keep using the application for my legal practice. My json is as follows(client info has been removed and replaced with generic info):
{
"data":[
{
"id":1035117666,
"client":
{
"id":905422394,
"name":"client1"
},
"display_number":"11-00012",
"description":"General",
"practice_area":
{
"id":4269978,
"name":"Business"
},
"status":"Open",
"open_date":"2011-12-14",
"close_date":null,
"billing_method":"hourly"
},
{
"id":1035117768,
"client":
{
"id":905422506,
"name":"client2"
},
"display_number":"12-00037",
"description":"HOA",
"practice_area":
{
"id":4269978,
"name":"Business"
},
"status":"Open",
"open_date":"2012-08-07",
"close_date":null,
"billing_method":"hourly"
}
],
"meta":
{
"paging":
{
"next":"https://app.goclio.com/api/v4/matters.json?fields=id%2C+client%7Bid%2C+name%7D%2C+display_number%2C+description%2C+practice_area%7Bid%2C+name%7D%2C+status%2C+open_date%2C+close_date%2C+billing_method&limit=2&page_token=BAh7BjoLb2Zmc2V0aQc%3D--b1ea3eba20c8acefbcdfc7868debd1e0ee630c64&status=Open"
},
"records":91
}
}
I built the following schema within my c# code:
public class MatterList
{
public List<Matter> matters { get; set; }
public Meta meta { get; set; }
}
public class Meta
{
public Paging paging { get; set; }
public int records { get; set; }
}
public class Paging
{
public string previous { get; set; }
public string next { get; set; }
}
[DeserializeAs(Name = "data")]
public class Matter
{
public int id { get; set; }
public Client client { get; set; }
public string display_number { get; set; }
public string description { get; set; }
public PracticeArea practice_area { get; set; }
public string status { get; set; }
public DateTime open_date { get; set; }
public DateTime close_date { get; set; }
public string billing_method { get; set; }
public string type = "matter";
}
public class PracticeArea
{
public int id { get; set; }
public string name { get; set; }
}
public class Client
{
public int id { get; set; }
public string name { get; set; }
}
When I run the RestSharp deserialize method I am sending the result to an object of type MatterList using the following line of code
MatterList matterList = jsonHandler.Deserialize<MatterList>(response);
I have so far attempted to deserialize without the Meta or Paging POCO classes with the accompanying change to the MatterList class (taking out the Meta property).
I have tried with and without the [DeserializeAs(Name="data")] directive.
I have tried to set the RootElement of the json response prior to deserialization.
I have tried to shorthand the deserialization by combining it with the Execute request code
IRestResponse<MatterList> matterList = client.Execute<MatterList>(request);
I have created a container class called MatterContainer which I placed between MatterList and Matter classes in the schema:
public class MatterList
{
public List<MatterContainer> matters { get; set; }
}
public class MatterContainer
{
public Matter matter { get; set; }
}
public class Matter
{
public int id { get; set; }
public Client client { get; set; }
public string display_number { get; set; }
public string description { get; set; }
public PracticeArea practice_area { get; set; }
public string status { get; set; }
public DateTime open_date { get; set; }
public DateTime close_date { get; set; }
public string billing_method { get; set; }
public string type = "matter";
}
I know I am getting the json response back from the server correctly so my request is proper and MatterList is not null after deserialization. The problem is that I cannot get the deserialization to actually populate the List matters within the MatterList class.
I have been looking at this off and on for two days and cannot get past this hurdle. If anyone sees what I did wrong I would greatly appreciate the insight, I am at a point where I cannot progress further with my application.
Thanks!
I think your [DeserializeAs(Name = "data")] attribute is in the wrong place. Try putting it in the root class instead:
public class MatterList
{
[DeserializeAs(Name = "data")]
public List<Matter> matters { get; set; }
public Meta meta { get; set; }
}
alternatively, try renameing that property to data

Converting JSON to Object fails - Cannot deserialize the current JSON object into System.Collections.Generic.List

I'm using the API of www.textlocal.in, which returns a JSON formatted object.
JSON
{
"warnings":[
{
"message":"Number is in DND",
"numbers":"917000000000"
}
],
"balance":900,
"batch_id":311110011,
"cost":1,
"num_messages":1,
"message":{
"num_parts":1,
"sender":"TXTLCL",
"content":"Test1"
},
"receipt_url":"",
"custom":"",
"inDND":[
"917000000000"
],
"messages":[
{
"id":"1350123781",
"recipient":918819437284
}
],
"status":"success"
}
My code with which I'm trying to parse the JSON:
private void button1_Click(object sender, EventArgs e)
{
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
}
public class jsonToObj
{
public warnings[] warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public messages[] messages { get; set; }
public string status { get; set; }
}
public class warnings
{
public string message { get; set; }
public string numbers { get; set; }
}
public class messages
{
public string id { get; set; }
public int recipient { get; set; }
}
public class message
{
public int num_part { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
I'm getting an exception with the following message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WindowsFormsApp1.Form2+jsonToObj[]]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize
correctly. To fix this error either change the JSON to a JSON array
(e.g. [1,2,3]) or change the deserialized type so that it is a normal
.NET type (e.g. not a primitive type like integer, not a collection
type like an array or List) that can be deserialized from a JSON
object. JsonObjectAttribute can also be added to the type to force it
to deserialize from a JSON object. Path 'warnings', line 1, position
12.'
First of all you have to figure out what your API returns.
Right now you're trying to parse a List of jsonToObj Arrays (List<jsonToObj[]>). You have to decide whether to use a jsonToObj[] or List<jsonToObj> or a simple jsonToObj which your API provides now:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
But this then throws:
JSON integer 918819437284 is too large or small for an Int32. Path 'messages[0].recipient', line 25, position 33."
So make sure you use a Long for that.
public class messages
{
public string id { get; set; }
public long recipient { get; set; }
}
Furthermore you can add inDND to your jsonToObj class if you need the info:
public class jsonToObj
{
...
public string[] inDND { get; set; }
...
}
Based on string you class structure should be like this :
public class Warning
{
public string message { get; set; }
public string numbers { get; set; }
}
public class Message
{
public int num_parts { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
public class Message2
{
public string id { get; set; }
public long recipient { get; set; }
}
public class RootObject
{
public List<Warning> warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public Message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public List<string> inDND { get; set; }
public List<Message2> messages { get; set; }
public string status { get; set; }
}
It looks like your class structure is not proper, Make use of visual studio and generate C# class from json string and then using that generated class try to deserialize class.
Read : Visual Studio Generate Class From JSON or XML
I simulated your problem and made the following changes that worked:
Change the method that deserializes to this:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
The result of the JSON you receive is not a List, so it will not work to deserialize to List<>.
The recipient property of the messages class receives values larger than an integer, so it must be transformed into a long like this:
public long recipient { get; set; }
These changes solve your problem.
Looks like this is a very old post, still thought of answering.
First of all, your Json data is singular which means, either
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
or
var a = JsonConvert.DeserializeObject<List<jsonToObj>>(richTextBox1.Text);
may not work for you.
You can either try:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
or
enclose the data with [ and ], which would do the trick.
make sure your parsing single object vs list of objects.

Can't deserialize an indexed name value pair child node C#

I'm running into an issue when I am trying to deserialize a webAPI GET call that returns a JSON object. The issue being one particular property is always null after being deserialized.
The JSON object looks like this:
{
"status":"OK",
"masterlist":{
"session":{
"session_id":intValue,
"session_name":"stringValue"
},
"0":{
"bill_id":intValue,
"number":"stringValue",
"change_hash":"stringValue",
"url":"stringValue",
"status_date":"dateValue",
"status":"stringValue",
"last_action_date":"dateValue",
"last_action":"stringValue",
"title":"stringValue",
"description":"stringValue"
},
"1":{
"bill_id":intValue,
"number":"stringValue",
"change_hash":"stringValue",
"url":"stringValue",
"status_date":"dateValue",
"status":"stringValue",
"last_action_date":"dateValue",
"last_action":"stringValue",
"title":"stringValue",
"description":"stringValue"
},
"2":{
"bill_id":intValue,
"number":"stringValue",
"change_hash":"stringValue",
"url":"stringValue",
"status_date":"dateValue",
"status":"stringValue",
"last_action_date":"dateValue",
"last_action":"stringValue",
"title":"stringValue",
"description":"stringValue"
}
}
}
As you can see the second property of masterlist isn't an array, that would make life too easy... But it looks more like a collection of name/value pairs. I have reviewed This post and the associated one listed within but they both pertain to if the name/value pair where at the root level where mine is not.
My method that I am using to deserialize is:
BillMaster billMasterList = new BillMaster();
using (HttpClient client = new HttpClient())
{
string json = Get("&op=getMasterList&state=TN");
billMasterList = JsonConvert.DeserializeObject<BillMaster>(json);
}
And the model classes the deserializer is binding to:
public class BillMaster
{
public string Status { get; set; }
public BillMasterList masterlist { get; set; }
}
public class BillMasterList
{
public BillMasterList_Session session { get; set; }
public Dictionary<int, BillMasterList_Array> BillMasterList_Array { get; set; }
}
public class BillMasterList_Array
{
public int bill_id { get; set; }
public string number { get; set; }
public string change_hash { get; set; }
public string url { get; set; }
public string status_date { get; set; }
public string status { get; set; }
public string last_action_date { get; set; }
public string last_action { get; set; }
public string title { get; set; }
public string description { get; set; }
}
When I run the code I don't throw any errors and I have values in my object except for BillMasterList_Array, that is always null. I'm obviously not doing something right but what it is alludes me.

Loss of a parameter in Deserialization with Json.NewSofton c # Xamarin forms

I have a problem with json deserialization with json newtonsoft. He can not deserialize all object parameters when calling the API.
Below is all my code.
As you can see with postapi the bees responding correctly all the parameters, it is when deserialize who loses a parameter.
newtonsoft json decode:
var response = await request.GetResponseAsync();
var stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var xml = reader.ReadToEnd();
String indexof = xml.Substring(76, xml.Length - 85);
USR_User_ReturnList = JsonConvert.DeserializeObject<List<OBJ_User>>(indexof);
object class:
public class OBJ_User
{
public int DLR_Id { get; set; }
public string DLR_Username { get; set; }
public string DLR_Password_Hash { get; set; }
public object DLR_Nome { get; set; }
public string DLR_Cognome { get; set; }
public int DLR_Tipo { get; set; }
public string DLR_Azienda { get; set; }
public object DLR_Telefono { get; set; }
public object DLR_Email { get; set; }
public int DLR_Abilitato { get; set; }
public object DLR_Time_Zone { get; set; }
public object DLR_Country { get; set; }
public string DLR_Culture { get; set; }
public object DLR_Email1 { get; set; }
public object DLR_MCC_Modello_Alias { get; set; }
public object DLR_Anagrafica { get; set; }
public object DLR_Firma { get; set; }
public bool IsFIMAP { get; set; }
public bool IsSTANDARD { get; set; }
public bool IsDealerOrFimap { get; set; }
public object DLR_Tipo_Esteso { get; set; }
public object DLR_Abilitato_Esteso { get; set; }
}
indexof json from StreamReader, from code:
[{"DLR_Id":15,"DLR_Username":"dealer02","DLR_Password_Hash":"P4ssw0rd2","DLR_Nome":null,"DLR_Cognome":"Rossi2","DLR_Tipo":0,"DLR_Azienda":"AziendaRossi2","DLR_Telefono":null,"DLR_Email":null,"DLR_Abilitato":1,"DLR_Time_Zone":null,"DLR_Country":null,"DLR_Culture":"","DLR_Email1":null,"DLR_MCC_Modello_Alias":null,"DLR_Anagrafica":null,"DLR_Firma":null,"IsFIMAP":false,"IsSTANDARD":false,"IsDealerOrFimap":true,"DLR_Tipo_Esteso":null,"DLR_Abilitato_Esteso":null}]
indexof from postman (right response), from api:
[{"DLR_Id":15,"DLR_Username":"dealer02","DLR_Password_Hash":"P4ssw0rd2","DLR_Nome":null,"DLR_Cognome":"Rossi2","DLR_Tipo":0,"DLR_Azienda":"AziendaRossi2","DLR_Telefono":null,"DLR_Email":null,"DLR_Abilitato":1,"DLR_Time_Zone":null,"DLR_Country":null,"DLR_Culture":"","DLR_Email1":null,"DLR_MCC_Modello_Alias":null,"DLR_Anagrafica":null,"DLR_Firma":null,"IsFIMAP":false,"IsSTANDARD":false,"IsDealerOrFimap":true,"DLR_Tipo_Esteso":null,"DLR_Abilitato_Esteso":null}]
Lost this parameter: IsDealerOrFimap
i have tested json with http://json.parser.online.fr/ and works, the conversion is right, but from code i lost one IsDealerOrFimap parameter.
The list is properly riempieta me, but all the items on the list do not have the IsDealerOrFimap parameter, loses it ... why?
unfortunately it takes me all parameters except one (IsDealerOfFimap), and can not understand why ... does anyone have any solution?
solution
i tryed format android device and now works correctly. mistery!
If a JSON object contains fields that can't be mapped to properties in the destination class, those fields are silently ignored.
The class you're deserializing your response into (Fimap.Models.DLR_User) simply does not have a IsDealerOrFimap property that the class you're serializing from has (OBJ_User).

C# Json.net - Deserialise JSON object and access nested values

I'm writing here because I think I used all resources I could get. There must be something terribly wrong with my abstraction/approach because I cannot
make it work properly. Task is quite simple - I need to iterate through nested list(??) generated from json input(or maybe I'm doing it wrong from the scratch).
Using jquery with this json works great but this time I need to process data on the server side.
I got json input(example extract below):
{
"services":[
{
"service_status":"CRITICAL",
"service_host":{
"host_status":2,
"host_address":"192.168.1.12",
"host_name":"test1app_srv",
"host_problem_has_been_acknowledged":0,
"host_has_comments":0,
"host_notifications_enabled":1,
"host_checks_enabled":1,
"host_is_flapping":0,
"host_scheduled_downtime_depth":0,
"host_notes_url":"",
"host_action_url":"",
"host_icon_image":"server.gif"
},
"service_description":"test1app_srv",
"service_problem_has_been_acknowledged":0,
"service_has_comments":0,
"service_accept_passive_service_checks":1,
"service_notifications_enabled":1,
"service_checks_enabled":1,
"service_is_flapping":0,
"service_scheduled_downtime_depth":0,
"service_notes_url":"",
"service_action_url":"",
"service_icon_image":"services.gif",
"service_state_duration":" 0d 0h 2m 7s",
"service_last_check":"04-27-2013 23:49:55",
"service_current_attempt":1,
"service_max_attempts":1,
"service_plugin_output":"CRITICAL - Throughput : Threshold '600' failed for value 720"
},
{}
]
}
from which, using http://json2csharp.com/ I've generated c# classes:
public class ServiceHost
{
public int host_status { get; set; }
public string host_address { get; set; }
public string host_name { get; set; }
public int host_problem_has_been_acknowledged { get; set; }
public int host_has_comments { get; set; }
public int host_notifications_enabled { get; set; }
public int host_checks_enabled { get; set; }
public int host_is_flapping { get; set; }
public int host_scheduled_downtime_depth { get; set; }
public string host_notes_url { get; set; }
public string host_action_url { get; set; }
public string host_icon_image { get; set; }
}
public class Service
{
public string service_status { get; set; }
public ServiceHost service_host { get; set; }
public string service_description { get; set; }
public int service_problem_has_been_acknowledged { get; set; }
public int service_has_comments { get; set; }
public int service_accept_passive_service_checks { get; set; }
public int service_notifications_enabled { get; set; }
public int service_checks_enabled { get; set; }
public int service_is_flapping { get; set; }
public int service_scheduled_downtime_depth { get; set; }
public string service_notes_url { get; set; }
public string service_action_url { get; set; }
public string service_icon_image { get; set; }
public string service_state_duration { get; set; }
public string service_last_check { get; set; }
public int service_current_attempt { get; set; }
public int service_max_attempts { get; set; }
public string service_plugin_output { get; set; }
}
public class NagiosRootObject
{
public List<Service> services { get; set; }
}
I managed to get the NagiosRootObject.services content but I cannot access values from Service.service_host.
I focused on an approach utilizing
NagiosRootObject obj = JsonConvert.DeserializeObject<NagiosRootObject>(json);
I have all above and I'm using Json.NET from http://json.codeplex.com.
I have tried hints from
Deserializing JSON object into a C# list
Deserialize JSON array(or list) in C#
C# - How to implement IEnumerator on a class
Deserialize Json to Class that implements Ienumerable in Asp.net
and few related but witho no luck.
Knowing that there is so many tutorials and not being able to make use of it makes me really sad..
Help would be appreciated. This post is the last resort for this task... I need serious tips. Thank You
Using json.NET the following code works: (after putting your json in a file called 'json.txt')
using (var reader = File.OpenText("json.txt"))
{
var ser = JsonSerializer.Create(null);
var jReader = new JsonTextReader(reader);
var grp = ser.Deserialize<NagiosRootObject>(jReader);
}
However, the list is populated by two objects, and in the 2nd one all the values are null. This is because you have an empty element {} in your json.
Edit: Your code works just as well in my test, so no need to change it.
Have you tried:
var obj = new JavaScriptSerializer().Deserialize<NagiosRootObject>(jsonString);
If you want to parse this json in server then it is better to parse this json into XML and utilize that xml to traverse. In server side coding xml traversing is easy. Especially in C#.
Convert the json into XMl or wise versa using newtonsoft dll. The code to parse json to XMl is
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
Dpwnload the dll from the link
http://json.codeplex.com/
I hope this will help you.

Categories

Resources