I want to store a settings object with every user (dont want a settings table) but I think I am on a competely wrong way. Thats the way I tried to get it done:
// this is the user model
public class AppUser: IdentityUser
{
public string FirstName {get; set;}
public string LastName {get; set;}
public UserSettings Settings {get; set;} // the desired object
}
// the settings class
[DataContract]
public class UserSettings
{
[DataMember]
public bool ANiceProperty {get; set;}
[DataMember]
public enum AnotherNiceEnumPropery {get; set;}
[DataMember]
public UserSettingsSubClass SubClass {get; set;}
// and so on...
}
// another sub-settings class
[DataContract]
public class UserSettingsSubClass
{
[DataMember]
public bool ANiceProperty {get; set;}
}
What is the best way to work with it, e.g. User.Settings.Property? In my crazy PHP and MySQL times I hat to create an array - serialize it - stored as string - deserialized it - back to array. But I think there is a better way, isnt it?
Anyway, you have to serialize the settings to string. I suggest you to use Json.Net library
Example of usage:
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
Related
I have the following JSON data:
{
"count": 2,
"data" : {
"items" : [
{
"id" : "1",
"letterheadline" : "This is a test",
"message" : "testing.. testing..",
"dateEntered" : "2018-01-01 18:00"
},
{
"id" : "2",
"letterheadline" : "Message two",
"message" : "testing.. testing.. testing..",
"dateEntered" : "2018-02-01 18:00"
},
]
}
}
I am trying to parse it into my own object that uses different values, i.e:
public class Message
{
public string title {get; set;}
public string body {get; set;}
public DateTime entryDate {get; set;}
}
public class Messages
{
public int itemCount {get; set;}
public List<Message> messages {get; set}
}
I am using
Messages messages = new JavaScriptSerializer().Deserialize<Messages>(result);
I have tried to use the following:
[JsonProperty("letterheadline")] (for example)
But I am still getting an error saying that it cannot be converted.
Is this because the JSON data itself is too deep to parse? Therefore would I need to create a new property Data inside my object that contains a list of Messages?
I have a class like so:
public class CareTaker
{
public int Id {get; set;}
public string name {get; set;}
public DateTime? DateTrained {get; set;}
public Certification Certification {get; set;}
public List<Certification> ExpiredCertifications {get; set;}
}
public class Certification
{
public int Id {get; set;}
}
and my JSON is like so:
{
"id": 1,
"name": "Dogtor",
"dateTrained": "01 Feb 2017",
"certification": 2,
"expiredCertifications": [1,5]
}
I know usually the JSON for Certification should really be like "certification": { "id": 2}, but, I don't have access to change the JSON so I have to figure out how to convert what I recieve ("certification": 2) to my object... Is there a way I can do this with either JavascriptSerializer or NewtonSoft please?
You could do something like this:
public class CareTaker
{
...
[NotMapped]
[JsonProperty(PropertyName = "certification"]
public int? CertificationId
{
get
{
return Certification?.Id;
}
set
{
Certification = new Certification { Id = value; }
}
}
[JsonIgnore]
public Certification Certification {get; set;}
...
}
To generate properly the classes, I would suggest copying the JSON and open the file where you want to store the classes and in visual studio go to EDIT->Paste Special->Paste JSON As Classes
then you would do something like this:
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonToClasses = ser.Deserialize<RootObject>(json);
In my POCO objects, I often inherit from other POCO objects. When I serialize a POCO object using JSON.NET, the order of properties gets all messed up.
Say, I have a Person class that looks like this:
public class Person
{
public int Id {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
}
Then I have an Employee class that inherits from Person class:
public class Employee : Person
{
public int DepartmentId {get; set;}
public string Title {get; set;}
}
When I serialize the Employee class, my JSON object looks like this:
{
"departmentId": 123,
"title": "Manager",
"id": 1234567,
"firstName": "John",
"lastName": "Smith"
}
Two questions:
Does the order of my JSON object properties matter?
Even if the order of properties doesn't matter, how can I get the properties to be in correct order i.e. I'd like to see the Person class properties first, then the Employee class properties.
Thank you for your help.
1.) No, order doesn't matter.
2.) You can use the [JsonProperty(Order=x)] attribute to control the order:
public class Employee : Person
{
[JsonProperty(Order = 1)]
public int DepartmentId { get; set; }
[JsonProperty(Order = 1)]
public string Title { get; set; }
}
From a quick test, order defaults to 0, is sorted from low to high, and properties with the same value of Order are sorted in an arbitrary order.
Actually, since my Object was already a JObject, I Had to use the following solution:
public class SortedJObject : JObject
{
public SortedJObject(JObject other)
{
var pairs = new List<KeyValuePair<string, JToken>>();
foreach (var pair in other)
{
pairs.Add(pair);
}
pairs.OrderBy(p => p.Key).ForEach(pair => this[pair.Key] = pair.Value);
}
}
and then use it like this:
string serializedObj = JsonConvert.SerializeObject(new SortedJObject(dataObject));
How can we hide the C# property where serializing with JSON.NET library. Suppose, we have class Customer
public class Customer
{
public int CustId {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public bool isLocked {get; set;}
public Customer() {}
}
public class Test
{
Customer cust = new Customer();
cust.CustId = 101;
cust.FirstName = "John"
cust.LastName = "Murphy"
string Json = JsonConvert.SerializeObject(cust);
}
JSON
{
"CustId": 101,
"FirstName": "John",
"LastName": "Murphy",
"isLocked": false
}
This object is converted to json, but i didn't specify the isLocked property. As library will serialize the entire class, is there any way to ignore a property during json serialization process or if we can add any attribute on the property.
EDIT:
Also, If we create two instance of Customer class in an array. if we didn't specify is locked property on the second instance, can we can property hide for second object.
JSON
{
"Customer": [
{
"CustId": 101,
"FirstName": "John",
"LastName": "Murphy",
"isLocked": false
},
{
"CustId": 102,
"FirstName": "Sara",
"LastName": "connie"
}
]
}
Use the JSON.Net attributes:
public class Customer
{
public int CustId {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
[JsonIgnore]
public bool isLocked {get; set;}
public Customer() {}
}
For more information: https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
Yes, marking your properties with JsonIgnore is probably best.
However, if you do want to chose at runtime, add a public bool ShouldSerialize{MemberName} to your class. When JSON.net Serialises it will call it, and if false, not serialise. isLocked is false by default, perhaps you do want to serialise it when its true, for example.
Mark that property with the JsonIgnore attribute.
Here's the content of my object:
- tree {ItemTree} ItemTree
id "0" string
im0 null string
- item Count = 1 System.Collections.Generic.List<ItemTree>
- [0] {ItemTree} ItemTree
id "F_1" string
im0 "something.gif" string
+ item Count = 16 System.Collections.Generic.List<ItemTree>
parentId "0" string
text "someName" string
+ Raw View
parentId null string
text "" string
And I build it dynamically, so it's bigger.
It is an object from this class:
public class ItemTree
{
public String id { get; set; }
public String text { get; set; }
public List<ItemTree> item { get; set; }
public string im0 { get; set; }
public String parentId { get; set; }
}
So, the class ItemTree has a property which itself is a List of ItemTree objects.
I want to convert this to string. When I make:
tree.ToString()
I only get:
tree.ToString() "ItemTree" string
But I want to convert the whole tree structure to string. How to do this?
You need to override the ToString() method in your class.
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code.
You can use XmlSerializer to serialize your object to XML.
You can Override the ToString Method of your class ItemTree
Or May be you can try with serializing with json-net
string json = JsonConvert.SerializeObject(tree);
You need to override the ToString method and print your tree representation there
public class ItemTree
{
public override string ToString()
{
return "Tree " + id +....
}
}
otherwise you will always see class name as result of base ToString()
If you override the ToString method, your implementation will be used by other code that calls ToString, simply because it's a standard method (inherited from Object).
Optionally you can implement a new method.
Either way, to avoid manually updating your method, you can generate a string using Json.Net like this:
string str = JsonConvert.SerializeObject(someObject);
Here is a sample from the documentation:
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
Nuget package: http://nuget.org/packages/Newtonsoft.Json/