Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, February 7, 2017

What is JSON?

JSON - JavaScript Object Notation

JSON is a lightweight data-interchange format created as an alternative to XML for asynchronous communication between a client and the server providing data.

Benefits of JSON vs. XML

  • lightweight
  • self describing
  • fairly easy to read

How is JSON data structured?

  • Data is stored as key / value pairs
  • Pairs are separated by commas (,)
  • Curly braces ({}) hold objects, set of key / value pairs
  • Square brackets ([]) hold arrays, an ordered collection of values
  • Keys must be a string written with double quotes
  • Values can be any of the following data types
    • String
    • Number
    • Boolean (true/false)
    • Null
    • Date
    • Object
    • Array

Data Type Examples:

String:

{“name”:”Brian Spencer”}

Number:

{“age”: 21}

Boolean:

{“hasKids”:true}

Null:

{“ssn”:null}

Date (ISO 8601 format):

{“dob”:”1996-01-01T04:45:14”}

Object:

{“name”:”Brian Spencer”,”dob”:”1996-01-01T04:45:14”,”age”:21,”ssn”:null}

Array:

{“kids”:[“Lili”,”Alex”,”Ana”]}


What languages can Serialize and Deserialize JSON?

Here are a few languages that either include or have libraries or packages that can be used to serialize and deserialize JSON.

Code example:  Serialize and deserialize JSON using C# and DataContractJsonSerializer

[DataContract(Name="parent")]
public class Parent
{
    //DataMember Name and Order properties allow you to indicate what the name 
    //should be when the property or variable is serialized and what order 
    //the key/values should be in
    [DataMember(Name="name", Order=1)]
    public string Name { get; set; }

    [DataMember(Name = "age", Order=2)]
    public int Age { get; set; }

    [DataMember(Name = "hasKids", Order=4)]
    public bool HasKids { get; set; }

    //Do not serialize this property
    [IgnoreDataMember]
    public DateTime DOB { get; set; }

    [DataMember(Name = "dob", Order=3)]
    private string DOBISO;

    [DataMember(Order=10)]
    public string SSN;

    //Optional:  Do some work when serializing the object
    [OnSerializing]
    public void OnSerializing(StreamingContext context)
    {
        this.DOBISO = this.DOB.ToString("o"); //Convert date string to ISO 8601
    }

    //Optional: Do some work when deserializing the object
    [OnDeserialized]
    public void OnDeserialized(StreamingContext content)
    {
        this.DOB = DateTime.Parse(this.DOBISO);
    }
}
//Create the parent object and populate it's properties
Parent parent = new Parent();
parent.Name = "Brian Spencer";
parent.Age = 21;
parent.DOB = new DateTime(1996, 1, 1);
parent.HasKids = true;

string jsonString = string.Empty; //variable to hold the JSON string

//Create an instances of the DataContractJsonSerializer class
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Parent));

//Create an instance of the MemorySteam class to write the serialized object to
using (MemoryStream mem = new MemoryStream())
{
    //Serialize the parent object to memory
    ser.WriteObject(mem, parent);
    //write the JSON string in memory to the jsonString variable using UTF8 encoding
    jsonString = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
    //Close the memory stream
    mem.Close();
}
Console.WriteLine(jsonString);
//{"name":"Brian Spencer","age":21,"dob":"1996-01-01T00:00:00.0000000","hasKids":true,"SSN":null}

//Convering the JSON back to an object
Parent parentFromJson = (Parent)ser.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)));

Monday, February 6, 2017

Return ISO 8601 dates when converting object to JSON using DataContractJsonSerializer

Below is an example of how to return a DataTime value in the ISO 8601 format when serializing an object using DataContractJsonSerializer.

[DataContract]
public class MyObjectWithDate
{
    [IgnoreDataMember]
    public DateTime MyDate { get; set; }

    [DataMember(Name = "mydate")]
    private string MyDateISO;

    [OnSerializing]
    public void OnSerializing(StreamingContext context)
    {
        this.MyDateISO = this.MyDate.ToString("o"); //Convert date string to ISO 8601
    }
}

Monday, July 13, 2015

C# Class Terminology

C# Class Terminology

Class

Class – template for an object. An object is an instance of a class.

Static Class - a class that cannot be instantiated. This type of class can be used when no internal fields are needed for the class methods to function.

Base Class – also known as the parent class. Base class is the class being "inherited”.

Derived Class – also known as the child class. Derived class "inherits” from another class.

Sealed Class – prevents the class from being "inherited”.

Abstract Class – a class that must be "inherited” to be used. An "Interface” is a completely abstract class. (Abstraction)

Enum Class – a class that contains constant (read-only) variables .

Fields and Properties

Fields – variables inside a class.

Property – used to "Encapsulate” fields. Properties are used to get and set the value of a field. They allow and control access to private fields. Properties allow fields to be "read-only” (get), "write-only” (set) , or "read-write” (get;set;).

Method

Method / Function – contain code / logic and perform actions.

Method Parameter – pass information to a method from another method or object. Used as variables inside the method. Parameters can have "default” values.

Method Return Values – return information to the calling method or object.

Constructor Method – method used to instantiate a new instance of the class. Typically used to set the initial value of fields. A class can have multiple constructors with different signatures (parameters).

Virtual Method – allows a "derived” class to "override” the functionality of the base class method. (Polymorphism).

Override Method – overrides the functionality of the base class method.

Abstract Method – a method that has no code and must have an override method in the derived (child) class. (Abstraction)

Access Modifiers

"Public” fields, methods, and properties can be accessed inside the class or by other objects.

"Private” fields, methods, and properties can be accessed inside the class only.

"Protected” fields, methods, and properties can be accessed inside the class or from a "Derived” class.

"Internal" fields, methods, and properties can only be access inside of the assemmbly.

Example Code: