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.
Related
Hello I have one json text inside this text there is one key which starts with $
string jsonText="{\"Version\":\"1.1\",\"Documents\":[{\"DocumentState\":\"Correct\",\"DocumentData\":{\"Name\":\"test\",\"$type\":\"Document\",\"Fields\":[{\"Name\":\"CustomerFullName\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerBirthDate\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentNumber\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0000000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"CustomerIsMarried\",\"$type\":\"Checkmark\",\"IsSuspicious\":false,\"Value\":true},{\"Name\":\"CustomerCounty\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerArea\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"CustomerAddress\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"11000000\",\"RecognizedValue\":\"\",\"Value\":\"\"},{\"Name\":\"DocumentGUID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentProposalID\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentCountry\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"FRA\",\"Value\":\"FRA\"},{\"Name\":\"DocumentCurrency\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"000\",\"RecognizedValue\":\"EUR\",\"Value\":\"EUR\"},{\"Name\":\"DocumentTo\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentFrom\",\"$type\":\"Text\",\"Value\":\"\"},{\"Name\":\"DocumentTotalNumberOfPages\",\"$type\":\"Text\",\"SuspiciousSymbols\":\"0\",\"RecognizedValue\":\"1\",\"Value\":\"1\"}]}}]}";
Console.WriteLine(jsonText);
var documentResult = JsonConvert.DeserializeObject<DocumentDTO>(jsonText);
and my class objects are below
public class DocumentDTO
{
public string Version { get; set; }
public List<DocumentInfo> Documents { get; set; }
}
public class DocumentInfo
{
public string DocumentState { get; set; }
public DocumentData DocumentData { get; set; }
public string DocumentAsBase64 { get; set; }
}
public class DocumentData
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonPropertyName("$type")]
public string type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
but it is not working not converting $type to type. How can I solve this problem ?
Thanks in advance
Kind Regards
That's because you're using JsonConvert from Newtonsoft.Json library and are marking property with JsonPropertyName attribute from System.Text.Json.Serialization. The two just don't play well together. Try replacing your JsonPropertyName with JsonProperty attribute from Newtonsoft.Json and it should work.
public class DocumentData
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public List<DocumentField> Fields { get; set; }
}
public class DocumentField
{
public string Name { get; set; }
[JsonProperty("$type")]
public string Type { get; set; }
public string SuspiciousSymbols { get; set; }
public string RecognizedValue { get; set; }
public string Value { get; set; }
}
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\"
This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);
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; }
}
I have the result of an API call which looks like:
{"Operations":[{"OperationId":"2","OperationObjectId":"Application","OperationName":"UnlockSession","OperationParameters":[{"Name":"viewModel","Value":"model"},{"Name":"returnUrl","Value":"https://"}],"OperationCaller":{"UserPrincipalName":"bob","ClientIPAddress":""},"OperationResult":"Succeeded","OperationStatus":200,"OperationRequest":{"Method":"POST","Url":""},"OperationStartedTime":"2013-08-20T12:04:17.5462357Z","OperationCompletedTime":"2013-08-20T12:04:17.9979469Z"}],"ContinuationToken":null}
Ideally I want to convert it to an object so I can do stuff like:
object.OperationObjectID; // gives Application
object.Method; // gives POST
object.OperationResult; // gives Succeeded
Does any one know how that is done? Does the JSON parse need to be aware of the format?
Thanks,
Andrew
you can use Json.Net as below
dynamic object = JObject.Parse(yorjsonstring);
object.Operations[0].OperationObjectID;
object.Operations[0].Method;
object.Operations[0].OperationResult;
rather than using dynamic object you can generate classes for your json and serialize to those classes like below.
you can get help of http://json2csharp.com/ site for generate classes
public class OperationParameter
{
public string Name { get; set; }
public string Value { get; set; }
}
public class OperationCaller
{
public string UserPrincipalName { get; set; }
public string ClientIPAddress { get; set; }
}
public class OperationRequest
{
public string Method { get; set; }
public string Url { get; set; }
}
public class Operation
{
public string OperationId { get; set; }
public string OperationObjectId { get; set; }
public string OperationName { get; set; }
public List<OperationParameter> OperationParameters { get; set; }
public OperationCaller OperationCaller { get; set; }
public string OperationResult { get; set; }
public int OperationStatus { get; set; }
public OperationRequest OperationRequest { get; set; }
public string OperationStartedTime { get; set; }
public string OperationCompletedTime { get; set; }
}
public class RootObject
{
public List<Operation> Operations { get; set; }
public object ContinuationToken { get; set; }
}
then
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonstring);
obj.Operations[0].OperationObjectID;
Try to use JavaScriptSerializer class: http://msdn.microsoft.com/ru-ru/library/system.web.script.serialization.javascriptserializer.aspx.