Hiding C# properties when serialize with JSON.NET - c#

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.

Related

How to inject specific property value while Json deserialization

I need to inject the specific property value to object that is being deserialize using JsonConvert.DeserializeObject method.
for example I have a class
public class Employee
{
public int EmployeeID {get; set;}
public string Name {get; set;}
public int OrgnizationID {get; set;}
}
Json
[
{
"employeeID": 1,
"name": "Neeraj"
},
{
"employeeID": 2,
"name": "Sam"
},
{
"employeeID": 3,
"name": "Jonson"
}
]
above json string converting to list of employee. Here I am looking a way to set the OrgnizationID with some value for full of list. I know I can set it after conversion, but god to have if I can set it along with conversion.
var employees = JsonConvert.DeserializeObject<List<Employee>>(jsonData);
in above line of code I am also passing the JsonSerializerSettings for some other purpose that not defined here just to keep question simple.

C# web API property object as string not object

I have an web API function that has a property that can take different shapes. Actually i need to save a json in database.
I will give you some examples
post body
{
"title":"example 1",
"type": "0",
"extraData": { "name": "bob",
// here is the catch this is first type of object let's say children
[{
"age": 10
"toys": "bear, goat"
},
{
"age": 18
"toys": "guitar"
}]
}
}
{
"title":"example 1",
"type": "1",
"extraData": { "name": "john",
// here is the catch this is first type of object let's say grandparents
[{
"age": 90
"cars": "honda civic"
},
{
"age": 18
"car": "renault megan, pegeout 206"
}]
}
}
Now let's assume that we can't merge grandparents and children together in a class so my classes will look something like:
public class Family{
public string Title {get; set;}
public string ExtraData {get; set;}
public int Type {get;set;}
}
public class ExtraData<T> where T: Person{
public string Name{get;set;}
public List<T> Persons {get;set;}
}
public class Person{
public int Age {get;set;}
}
public class Child : Person{
public string Toys{get;set;}
}
public class Grandparent : Person{
public string Cars{get;set;}
}
In the api method I was thinking to do something like:
public void Save(Family model)
{
// to parse extraData my idea was to
switch(mode.Type)
{
case 0: var childrens = JsonConvert.DeserializeObject<ExtraData<Child>>(model.ExtraData);
// do stuff
break;
case 1: var grandparents = JsonConvert.DeserializeObject<ExtraData<Child>>(model.ExtraData);
// do stuff
break;
}
// save the object
}
The issue is that on the api call I get nothing in the extraData string. And I can't put in Family something like
public ExtraData<Person> Persons {get;set;}
because it will deserialize to the base type and I will lose the subclass information.
I know is to do something like json stringify but I would like this to be my last resort. Also i have tried to use dynamic instead of Family but I still need to deserialze it and having same issue.
What is the best approach here?

Deserialize to object with custom object property

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);

ASP.MVC Settings Object Model Binding

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);

Order of properties get messed up when serialized by JSON.NET

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));

Categories

Resources