While I am trying to call the
`var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})`
it keeps throwing me unable to deserialize exception.
To check if my json string was well formed i decided to
Parse the string and called
JsonSchema schema = JsonSchema.Parse({myjsonString});
now i get the error below, not quite sure what it means
Additional information: Expected object while parsing schema object,
got String. Path ''
**UPDATE**
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}"
UPDATE 2
"\"{\\\"Id\\\":5,\\\"Username\\\":\\\"Sid\\\",\\\"FirstName\\\":\\\"Siddharth \\\",\\\"LastName\\\":\\\"Kosta\\\",\\\"Email\\\":\\\"Skosta#gmail.com\\\",\\\"Password\\\":\\\"PAssword\\\",\\\"GravatarHash\\\":\\\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8c4bcd5adc1?d=retro&?s=50\\\",\\\"Country\\\":\\\"India\\\",\\\"OrganizationId\\\":1,\\\"IsLocked\\\":false,\\\"CreatedDate\\\":\\\"2013-12-13T02:34:28.037\\\",\\\"UpdatedDate\\\":\\\"2013-12-13T02:34:28.23\\\",\\\"DataLoaded\\\":true}\""
The User Model
public class UserModel
{
public Int32 Id { get; set; }
public String Username { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String GravatarHash { get; set; }
public String Country { get; set; }
public Int32 OrganizationId { get; set; }
public Boolean IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
}
I also tried
public String CreatedDate { get; set; }
public String UpdatedDate { get; set; }
thinking if the dates were causing a problem
Update:
It works perfectly fine with your UserModel, at least for me.
Assume you have such UserModel:
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
var input =
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}";
var userModel = JsonConvert.DeserializeObject<UserModel>(input);
I think the problem with your model, can you please provided it?
It looks to me like your JSON is getting double serialized. (Having a bunch of extra backslashes in your JSON is a symptom of this.) I notice in the comments on another answer that you said you are using Web API. The Web API framework takes care of serialization for you, so you do not need to call JsonConvert.SerializeObject() in those methods. Instead just return your result directly. Then you should be able to deserialize it normally in your client. See this question.
Is there a reason why you have the curly braces in
var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})
That seems like the source of the error. Change it to:
var obj = JsonConvert.DeserializeObject<UserModel>(myjsonString)
You're missing the DataLoaded property.
public bool DataLoaded { get; set; }
In future, use this website to generate your C# classes from JSON.
http://json2csharp.com/
EDIT:
Try this step by step...
Copy and paste this class exactly as is.
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
Now in the console have this:
var jsonString = #"{""Id"":5,""Username"":""Sid"",""FirstName"":""Sid "",""LastName"":""LastSid"",""Email"":""test#gmail.com"",""Password"":""sample"",""GravatarHash"":""http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50"",""Country"":""Moon"",""OrganizationId"":1,""IsLocked"":false,""CreatedDate"":""12/13/2013 2:34:28 AM"",""UpdatedDate"":""12/13/2013 2:34:28 AM"",""DataLoaded"":true}";
var user = JsonConvert.DeserializeObject<UserModel>(jsonString);
Console.WriteLine(user.Country);
Console.ReadLine();
Related
I using Realm database at my Xamarin project
I have realm object with this model
public class UserModel: RealmObject
{
public string Id { get; set;}
public string Email { get; set; }
public string Password { get; set; }
public byte[] UserAvatar { get; set; }
public string ApiKey { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Birthday { get; set; }
public int Country_id { get; set; }
public bool IsAuthorized { get; set; }
public string Base64Avatar { get; set; }
public string Telephone { get; set; }
}
I need to update Name property.
How I try to do this
var realm = Realm.GetInstance();
var user_check = realm.All<UserModel>().First();
user_check.Name = "Test"
and get this error
How I can fix this?
Adding/Updating/Deleting to Realm object must be done inside a transaction, easiest way is to wrap it in Write method.
realm.Write(() =>
{
user_check.Name = "Test";
});
For more info, check the Rleam Write docs
i am trying to convert JSON to object following is my json
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":"payment.captured","contains":["payment"],"payload":{"payment":{"entity":{"id":"pay_AKR45WLH0g1ANu","entity":"payment","amount":100,"currency":"INR","status":"captured","order_id":"order_AKR41LsWIgOAB1","invoice_id":null,"international":false,"method":"netbanking","amount_refunded":0,"refund_status":null,"captured":true,"description":"Admission Fees","card_id":null,"bank":"SBIN","wallet":null,"vpa":null,"email":"xxxxx.xxxx#xxx.xxx","contact":"xxxxx","notes":{"address":"NA","merchant_order_id":"2516"},"fee":2,"tax":0,"error_code":null,"error_description":null,"created_at":1528367383}}},"created_at":1528367384}
and the code I am trying to convert to object is
jsonString = JsonConvert.SerializeObject(documentContents);
RazorPayPayload desJsonString = JsonConvert.DeserializeObject<RazorPayPayload>(jsonString);
and the classes where I want to deserialized
public class RazorPayPayload
{
public string entity { get; set; }
public string account_id { get; set; }
public string events { get; set; }
public List<string> contains { get; set; }
public payments payload { get; set; }
public string created_at { get; set; }
}
public class payments
{
public Entities payment { get; set; }
}
public class notes
{
public string address { get; set; }
public string merchant_order_id { get; set; }
public string source { get; set; }
}
public class Entities
{
public Entity entity { get; set; }
}
public class Entity
{
public string id { get; set; }
public string entity { get; set; }
public string amount { get; set; }
public string currency { get; set; }
public string order_id { get; set; }
public string invoice_id { get; set; }
public string international { get; set; }
public string method { get; set; }
public string amount_refunded { get; set; }
public string refund_status { get; set; }
public string captured { get; set; }
public string description { get; set; }
public string card_id { get; set; }
public string bank { get; set; }
public string wallet { get; set; }
public string vpa { get; set; }
public string email { get; set; }
public string contact { get; set; }
public notes notes { get; set; }
public string fee { get; set; }
public string tax { get; set; }
public string error_code { get; set; }
public string error_description { get; set; }
}
I am getting the error "Error converting value to type 'FeePayr_Razor_Webhook.RazorPayPayload'"
Have you tried changing:
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":
to
{"entity":"event","account_id":"acc_8yTsyb2WJOlcka","events":
That would better match your class definition. Or rename your class field to event.
There is a useful visual studio function for converting a json object to c# classes.
Copy the JSON into the clipboard. (helps if the JSON object properties holds data, to determine the data type)
Go to visual studio and place cursor where you'd like to paste in the c# classes.
click edit => paste special => paste json as classes
String str ="{\"_id\":\"eta_emp_1\",\"_rev\":\"446-195e9341df50aeed33d2cb833420b100\",";
str+="\"channels\":[\"ch_pri-eta_org\"],\"doc_type\":\"emp\",\"downloaded\":true,";
str+="\"eta_code\":\"abhi\",\"f_name\":\"Abhilash\",\"isactive\":true,";
str+="\"isadmin\":true,\"l_name\":\"Dhondalkar\",";
str+="\"lat\":17.69967582522918,\"lon\":75.89857880026102,";
str+="\"m_name\":\"Dheeraj\",\"mod_at\":1494693566503,\"mod_by\":\"eta_emp_1\",";
str+="\"org_id\":\"eta_org\",\"pwd\":\"abcde\",";
str+="\"reported_by\":[\"e27f41e7-5b84-4c86-838e-97598b4d20a0\",\"8daa0901-f6e8-4fdd-b41c-658aa901899d\",";
str+="\"9bf72297-481c-4d59-a0f4-d5549cb60e27\",\"2e5ce994-2cfb-4e62-88f8-ff1d3a069ca0\"]}";
UserDetails userDetails = JsonConvert.DeserializeObject<UserDetails>(str);
public class UserDetails
{
String _id{get;set;}
String _rev { get; set; }
String[] channels{get;set;}
String doc_type{get;set;}
bool downloaded{get;set;}
String eta_code{get;set;}
String f_name{get;set;}
bool isactive { get; set; }
bool isadmin { get; set; }
long l_name{get;set;}
long lat{get;set;}
String lon{get;set;}
String m_name{get;set;}
long mod_at{get;set;}
String mod_by{get;set;}
String org_id{get;set;}
String pwd{get;set;}
String[] reported_by{get;set;}
}
All values are set to null.
Not able to figure out issue. Pl help
This class should work:
public class UserDetails
{
public string _id { get; set; }
public string _rev { get; set; }
public List<string> channels { get; set; }
public string doc_type { get; set; }
public bool downloaded { get; set; }
public string eta_code { get; set; }
public string f_name { get; set; }
public bool isactive { get; set; }
public bool isadmin { get; set; }
public string l_name { get; set; }
public double lat { get; set; }
public double lon { get; set; }
public string m_name { get; set; }
public long mod_at { get; set; }
public string mod_by { get; set; }
public string org_id { get; set; }
public string pwd { get; set; }
public List<string> reported_by { get; set; }
}
More help:
http://json2csharp.com
Based on my previous experience with JSON.NET, it can be a bit tricky the translation from JSON to the right class. The web site above have provided me all the time the right class. The only exception is the Wikipedia API because it's a dynamic API and you need to do a small trick.
Also, keep in mind all properties must be public because if something is private (like in your question), it is not going to be accessible by the translator or anything else. I hope it's helpful.
Either mark all the properties in your class as public, or explicity add JsonProperty attribute to each property as follows:
public class UserDetails
{
[JsonProperty("_id")]
String _id { get; set; }
...
}
When using Json Validator I got "The root JSON data must represent an object or an array", therefore indicating that your JSON is most likey not correct.
This is why the string cannot be serialized to your class, leaving the properties null.
You should show us your serialization process to find out about where the error is.
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 want to create my first application using the EF 4.1 Code First Model. I want to model a magazine subscription but just want to check that my POCO classes are fit for purpose.
The following are my classes. Am I missing anything?
Should Customer be a member of Subscription or should it be just that List be a member of Customer?
Thanks.
public class Subscription
{
public int SubscriptionID { get; set; }
public string CardNumber { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public decimal NetPrice { get; set; }
public decimal Tax { get; set; }
public decimal Discount { get; set; }
public string PromotionalCode { get; set; }
public Customer Customer{ get; set; }
}
public class Customer {
public int CustomerID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public PostalAddress PostalAddress { get; set; }
public string EmailAddress { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public DateTime DateOfBirth { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public bool Valid { get; set; }
public IList<Subscription> Subscriptions { get; set; }
public bool MailMarketing { get; set; }
public bool PartnerMailMarketing { get; set; }
}
public class PostalAddress
{
public int ID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public string Region { get; set; }
public string Country { get; set; }
}
If a Customer have X suscriptions, every suscription should have the customerID so you need that in your Suscription class (public int CustomerID {get; set;}).
OTOH, I think that you have to put that Customer reference as virtual and the suscription one (I don't know why).
Maybe Im wrong but that works for me.
Anyway, what's your problem?
Your models look correct. You don't necessarily need the Customer property in the Subscription class, but it does help if you want to retrieve a specific Subscription and then want to find the customer that is tied to that subscription. In that instance you can then do var customer = mySub.Customer instead of querying for a customer with the specific subscription id.