Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
I am trying to deserialize the json string in C#. Following is jsonstring I used. But after deserialize it is giving null value. So what's going wrong with me?
string res = #"{ ""root"":{""EmployeeMaster"":{""EmployeeMasterData"":[{""BasicDetails"":{ ""BasicDetail"":{ ""Action"":""Update"",""EmployeeCode"":""0076"",""L2ManagerCode"":2911}}},{""BasicDetails"":{""BasicDetail"":{ ""Designation"":""Branch Incharge"",""Action"":""Update"",""EmployeeCode"":1786,""SubDepartment"":""Branch Manager"",""Department"":""Operations"",""JOBROLE"":""Branch Manager"",}}},{""DependentDetails"":{""DependentDetail"":{""DateOfBirth"":""1972-07-31"",""DependentName"":""Ramani"",""Action"":""Create"",""EmployeeCode"":2923,""Address"":"""",""RelationshipType"":""Mother"",""Gender"":"""",""IsDependent"":""No""}}},{""ContactDetails"":{""ContactDetail"":[{""AddressLine2"":""Turvekere"",""AddressLine1"":""Hallada Hosahalli"",""Action"":""Update"",""Country"":""India"",""City"":""Tumkur"",""Pincode"":572227},{""AddressLine2"":"""",""AddressLine1"":"""",""Action"":""Update"",""State"":"""",""Country"":"""",""City"":"""",""Pincode"":""""}]}},{""BasicDetails"":{""BasicDetail"":{""Action"":""Create"",""L2ManagerName"":""Ratheesh P R"",""IsDisabled"":""No"",""L1ManagerCode"":2771,""SubDepartment"":""Collection Assistant"",""Gender"":""Male"",""EmploymentType"":""Permanent"",""Department"":""Operations"",""L1ManagerName"":""Arun K K"",""Designation"":""Collection Assistant"",""EmployeeCode"":201021,""L2ManagerCode"":2564,""FirstName"":""Vishnu"",""Title"":""Mr."",""EmploymentStatus"":""Active"",""MiddleName"":"""",""DisabilityType"":"""",""OfficialMailID"":"""",""Nationality"":""IND"",""DateOfRelieving"":"""",""DateOfJoining"":""2022-01-20"",""JOBROLE"":"""",""LastName"":""G"",""BirthDate"":""1995-08-28""}}}]}}}";
It's not working, because the primitive object is invalid. can anyone please help me to create the class file. thanks in advance
try this, it was tested in visual studio
var jsonParsed = JObject.Parse(json);
List<EmployeeMasterData> employeeMasterData = jsonParsed["root"]["EmployeeMaster"]
["EmployeeMasterData"].Select(x => AddItems(x)).ToList();
public static EmployeeMasterData AddItems(JToken jt)
{
var emd = new EmployeeMasterData();
foreach (var element in ((JObject)jt).Properties())
{
if (element.Name == "BasicDetails")
emd.BasicDetails = element.Value.ToObject<BasicDetails>();
if (element.Name == "DependentDetails")
emd.DependentDetails = element.Value.ToObject<DependentDetails>();
if (element.Name == "ContactDetails")
emd.ContactDetails = element.Value.ToObject<ContactDetails>();
}
return emd;
}
classes
public class EmployeeMasterData
{
public BasicDetails BasicDetails { get; set; }
public DependentDetails DependentDetails { get; set; }
public ContactDetails ContactDetails { get; set; }
}
public class EmployeeMaster
{
public List<EmployeeMasterData> EmployeeMasterData { get; set; }
}
public class Root
{
public EmployeeMaster EmployeeMaster { get; set; }
}
public class BasicDetail
{
public string Action { get; set; }
public string EmployeeCode { get; set; }
public int? L2ManagerCode { get; set; }
public string Designation { get; set; }
public string SubDepartment { get; set; }
public string Department { get; set; }
public string JOBROLE { get; set; }
public string L2ManagerName { get; set; }
public string IsDisabled { get; set; }
public string L1ManagerCode { get; set; }
public string Gender { get; set; }
public string EmploymentType { get; set; }
public string L1ManagerName { get; set; }
public string FirstName { get; set; }
public string Title { get; set; }
public string EmploymentStatus { get; set; }
public string MiddleName { get; set; }
public string DisabilityType { get; set; }
public string OfficialMailID { get; set; }
public string Nationality { get; set; }
public string DateOfRelieving { get; set; }
public string DateOfJoining { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}
public class BasicDetails
{
public BasicDetail BasicDetail { get; set; }
}
public class DependentDetail
{
public string DateOfBirth { get; set; }
public string DependentName { get; set; }
public string Action { get; set; }
public string EmployeeCode { get; set; }
public string Address { get; set; }
public string RelationshipType { get; set; }
public string Gender { get; set; }
public string IsDependent { get; set; }
}
public class DependentDetails
{
public DependentDetail DependentDetail { get; set; }
}
public class ContactDetail
{
public string AddressLine2 { get; set; }
public string AddressLine1 { get; set; }
public string Action { get; set; }
public string Country { get; set; }
public string City { get; set; }
public object Pincode { get; set; }
public string State { get; set; }
}
public class ContactDetails
{
public List<ContactDetail> ContactDetail { get; set; }
}
Generally, I would suggest the NewtonSoft JSON library if you are working with JSON. You can serialize and deserialize JSON to class, and class to JSON.
With this library you must not parse JSON by yourself.
JSON Library
First of all, there are some errors in the Json format. There is an incorrect use of the icon. Additionally, if you specify string for Json, the \ add symbol is required for each ".
You do not need to write # in front of the string this time.
like this
\"DateOfJoining\":\"2022-01-20\"
Related
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);
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; }
}
JSON response string send by client:
{ "{\"user_id\":\"\",\"school_id\":\"1\",\"user_name\":\"pfirstname1#example.com\",\"firstname\":\"pfirstname1\",\"surname\":\"psurname1\",\"type\":\"P\",\"phoneno\":\"1446863\",\"mobileno\":\"3614632\",\"address\":\"mehdipatnam\",\"relation\":\"Father\",\"date_created\":\"\",\"student_dto\":": { "{\"student_id\":0,\"user_id\":0,\"firstname\":\"sfirstname1\",\"surname\":\"ssurname1\",\"rollno\":1,\"class_id\":\"2\",\"school_id\":\"1\",\"address\":\"mehdipatnam\",\"remarks\":\"\",\"date_created\":\"\"}]}": "" }}
Then to deserialize this I'm doing this step:
dynamic data = new JavaScriptSerializer().Deserialize(response.ToString(), typeof(object));
Then when I look in to the debugger I can see:
[0] {[{"user_dto":{"user_id":"","school_id":"1","user_name":"pfirstname1#example.com","firstname":"pfirstname1","surname":"psurname1","type":"P","phoneno":"1446863","mobileno":"3614632","address":"mehdipatnam","relation":"Father","date_created":"","student_dto":, System.Collections.Generic.Dictionary`2[System.String,System.Object]]} System.Collections.Generic.KeyValuePair<string,object>
But how do I access the values?
I'm going into this assuming that the mess you posted as JSON should actually be the following after all the \" and erroneous quotes are removed.
{
"user_id":"",
"school_id":"1",
"user_name":"pfirstname1#example.com",
"firstname":"pfirstname1",
"surname":"psurname1",
"type":"P",
"phoneno":"1446863",
"mobileno":"3614632",
"address":"mehdipatnam",
"relation":"Father",
"date_created":"",
"student_dto":
{
"student_id":0,
"user_id":0,
"firstname":"sfirstname1",
"surname":"ssurname1",
"rollno":1,
"class_id":"2",
"school_id":"1",
"address":"mehdipatnam",
"remarks":"",
"date_created":""
}
}
If that's the case, then json2csharp.com gives the following as the classes to deserialize into:
public class StudentDto
{
public int student_id { get; set; }
public int user_id { get; set; }
public string firstname { get; set; }
public string surname { get; set; }
public int rollno { get; set; }
public string class_id { get; set; }
public string school_id { get; set; }
public string address { get; set; }
public string remarks { get; set; }
public string date_created { get; set; }
}
public class RootObject
{
public string user_id { get; set; }
public string school_id { get; set; }
public string user_name { get; set; }
public string firstname { get; set; }
public string surname { get; set; }
public string type { get; set; }
public string phoneno { get; set; }
public string mobileno { get; set; }
public string address { get; set; }
public string relation { get; set; }
public string date_created { get; set; }
public StudentDto student_dto { get; set; }
}
Now you should be able to deserialize directly into that type.
new JavaScriptSerializer().Deserialize<RootObject>(response.ToString());
Guyz
I am trying to parse a JSON string into object. I have the below entity in which I am parsing the JSON string
public class Room : BaseEntity
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public List<RoomImage> RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
//public List<Equipment> Equipment { get; set; }
public override string ToString()
{
return this.Name;
}
}
public class RoomImage : BaseEntity
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
}
public class InternalOnly : BaseEntity
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class BaseEntity
{
}
I am using below method to parse the string into object
public static T ParseObjectToJSON<T>(string responseText)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText)))
{
var rootObject = serializer.ReadObject(stream);
//return Convert.ChangeType(rootObject,typeof(T),System.Globalization.CultureInfo.CurrentCulture.TextInfo);
return (T)rootObject;
}
}
Below is the JSON string which I am trying to parse
https://docs.google.com/document/d/1k81M_UxIrXpHUPQNDUCHDfNw1wY7LM4mAaXjwpYMshk/edit?usp=sharing
The below json string is working
https://docs.google.com/document/d/1uQNwMmSyEZSolyxUVJl6gXzZPr6aRAf_WAogmUvVqt4/edit?usp=sharing
While parsing I get below error
The data contract type 'GAP.Entities.Room' cannot be deserialized because the member 'RoomImage' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.
Note- RoomImage is marked public in the entity class. I get this error only when JSON string contains RoomImage array string otherwise no erro.
Any help is highly appreciated.
Thanks
Vinod
You can download and deserialize an JSON using Newtonsoft.
You have to reference the following DLL, and after that you can try this:
List<Room> deserializedObj = (List<Room>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, typeof(List<Room>));
The problem with your json is that if RoomImage has a single element, your service returns it as an object {} not as an array of objects [{}].
So If you want to use type-safe classes in your code(since dynamically accessing is also possible) you should pre-process your json before deserializing. Below code works (of course, as everybody says, using Json.Net)
string json = your__json__string
//PreProcess
var jobj = JObject.Parse(json);
foreach (var j in jobj["ObjectList"])
{
if (!(j["RoomImage"] is JArray))
{
j["RoomImage"] = new JArray(j["RoomImage"]);
}
}
var obj = JsonConvert.DeserializeObject<RootObject>(jobj.ToString());
public class InternalOnly
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class RoomImage
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdateDate { get; set; }
public string LastUpdateId { get; set; }
}
public class ObjectList
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public RoomImage[] RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public string IsRestrictedRoom { get; set; }
public InternalOnly InternalOnly { get; set; }
public object Equipment { get; set; }
}
public class RootObject
{
public List<ObjectList> ObjectList { get; set; }
}
The property RoomImage is public but your class probably isn't.
Make sure the RoomImage class is also marked public. That should solve the problem.
Alternatively use a library like JSON.NET that can do this deserialization without the need for public classes.
So I have a set of classes:
public class CallQueueRequest
{
public string ACK { get; set; }
public string ERROR { get; set; }
public Agent AGENT { get; set; }
public Skill SKILL { get; set; }
public string TIME { get; set; }
}
public class Agent
{
public string has_result { get; set; }
public List<Agents> agents { get; set; }
}
public class Agents
{
public string display_name { get; set; }
public string time_in_state { get; set; }
public string state { get; set; }
public string callstakentoday { get; set; }
public string avaya_skill_num { get; set; }
}
public class Skill
{
public string has_result { get; set; }
public string num_skills { get; set; }
public List<Skills> skills { get; set; }
}
public class Skills
{
public string display_name { get; set; }
public string avaya_skill_num { get; set; }
public string callsinqueue { get; set; }
public string callstoday { get; set; }
public string abantoday { get; set; }
public string lwt { get; set; }
public string ewt { get; set; }
public string servicelvl { get; set; }
public string avgspeedans { get; set; }
public string talktime { get; set; }
}
And I have this Json:
{
"ACK":"SUCCESS",
"ERROR":null,
"AGENT":{
"has_results":1,
"agents":[
{
"display_name":"John Doe",
"time_in_state":"378",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
},
{
"display_name":"Jane Joe",
"time_in_state":"220",
"state":"Acd",
"callstakentoday":null,
"avaya_skill_num":"81"
}
]
},
"SKILL":{
"has_results":1,
"num_skills":1,
"skills":[
{
"display_name":"QueueName",
"avaya_skill_num":"81",
"callsinqueue":"1",
"callstoday":"29",
"abandtoday":"1",
"lwt":"74",
"ewt":"223",
"servicelvl":"86",
"avgspeedans":"35",
"talktime":"873"
}
]
},
"TIME":1355864270
}
I am using this code:
object qr = JsonConvert.DeserializeObject(jsonString);
This does not seem to be converting from Json to the complex class properly. Can someone assist me with this? I think its just a small mistake.
I was able to find some info on what I'm trying to do. If anyone finds this question, here is the answer