Conditional Property Serialization Property To JSON - VB.net
Conditional Property Serialization
Json.NET has the ability to conditionally serialize properties by placing a ShouldSerialize method on a class. This functionality is similar to the
XmlSerializer ShouldSerialize feature.
ShouldSerialize
To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name
with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be
serialized, if it returns false then the property will be skipped.
Live Code
We need to exclude hsn and Doc_issue when they are nothing in runtime (Same is done Nothing when not to be Serialized)
Public Structure Json_Parent
Public Property gstin As String
Public Property fp As String
Public Property version As String
Public Property hash As String
Public Property b2b As List(Of b2b)
Public Property hsn As hsn
Public Property doc_issue As doc_issue
Public Property exp As List(Of exp)
' Make sure this is Function and WORD [ShouldSerialize] Followed by Name of Property which is to be Excluded from serialization
Public Function ShouldSerializehsn() As Boolean
If IsNothing(hsn.data) = True Then
Return False
Else
Return True
End If
End Function
Public Function ShouldSerializedoc_issue() As Boolean
If IsNothing(doc_issue.doc_det) = True Then
Return False
Else
Return True
End If
End Function
End Structure
While using the
ParentJson.gstin = CompanyGSTinNo
ParentJson.fp = Format(FromDate, "MMyyyy")
ParentJson.version = "GST2.4"
ParentJson.hash = "hash"
ParentJson.hsn = Nothing
ParentJson.doc_issue = Nothing
Employee class with a ShouldSerialize method
Copy
public class Employee
{
public string Name { get; set; }
public Employee Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property if an employee is their own manager
return (Manager != this);
}
}
ShouldSerialize output
Copy
Employee joe = new Employee();
joe.Name = "Joe Employee";
Employee mike = new Employee();
mike.Name = "Mike Manager";
joe.Manager = mike; // mike is his own manager
// ShouldSerialize will skip this property
mike.Manager = mike;
mike.Manager = mike;
string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);
// [
// {
// "Name": "Joe Employee",
// "Manager": {
// "Name": "Mike Manager"
// }
// },
// {
// "Name": "Mike Manager"
// }
// ]
Comments
Post a Comment