Convert a JSON string into a C# object


There could be scenarios in our project wherein we consume a service which returns back a JSON message. These JSON message is infact a stringified version of an object and are recognized as a simple string format by our server side. Decoding them gets difficult at the first shot.

But C# itself has got a solution for this. And that is the JavaScriptSerializer object from the namespace System.Web.Script.Serialization;

Let me take you through the conversion of a JSON string to a custom C# object here. Its pretty simple!!

#1: ADD the following namespace to your code

Using System.Web.Script.Serialization;

#2: INITIALIZE the JavaScriptSerializer object

JavaScriptSerializer jss= new JavaScriptSerializer();

#3: IMPLEMENT the Deserialize method of JavaScriptSerializer, passing two important information – one is the custom object (MyCustomObject) and the JSON string (jsonResponse)

MyCustomObject user = jss.Deserialize<MyCustomObject>(jsonResponse);

#4: DEFINE the MyCustomObject class in your code. Ensure that the object structure matches the JSON string format.

public class MyCustomObject

{

public string myProperty1;

public string myProperty2;

}

You can then use the Deserialized object “user” and get its properties like:
user.Property1 or user.Property2.

For information on the Serialization of C# object to JSON, you can refer my previous post:

Generate JSON String Output in C#

 

Happy Coding!!!

Generate JSON string output in C#


This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.

We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:

using System.Web.Script.Serialization;

The code snippet below show how its done:

//Namespace for the JavascriptSerializer object

using System.Web.Script.Serialization;

public string GenerateJSONString(List<myObject> myCustomList)

{

//Initialize the JavascriptSerializer object   

JavaScriptSerializer serializer = new JavaScriptSerializer();

//Initialize a stringbuilder object to hold the final JSON output     

StringBuilder jsonBuilder = new StringBuilder();

//Generate the JSON string

serializer.Serialize(myCustomList, jsonBuilder);

//Return the JSON string

return Convert.ToString(jsonBuilder);

}

This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.

In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.

.Net Coding Standards Part2 : Coding Practices


This post is in continuation to my previous post “.Net Coding Standards Part1 : Naming conventions and style”. If you wish to go through it again, you can access it here.

Here i will be taking you through some Coding practices in DotNet coding. I would request you to go through them slowly and with no rush. It is essential you keep note of these practices before you start coding.

1.    Avoid putting multiple classes in a single file.

2.    A single file should contribute types to only a single namespace. Avoid having multiple namespaces in the same file.

3.    Avoid files with more than 500 lines (excluding machine-generated code).

4.    Avoid methods with more than 200 lines.

5.    Avoid methods with more than 5 arguments. Use structures for passing multiple arguments.

6.    Lines should not exceed 120 characters.

7.    Do not manually edit any machine-generated code.

  • a.    If modifying machine generated code, modify the format and style to match this coding standard.
  • b.    Use partial classes whenever possible to factor out the maintained portions.

8.    Avoid comments that explain the obvious. Code should be self-explanatory. Good code with readable variable and method names should not require comments.

9.    Document only operational assumptions, algorithm insights and so on.

10.    Document the code with C# documentation comments.

11.    With the exception of zero and one, never hard-code a numeric value. Always declare a constant instead.

12.    Use the const directive only on natural constants such as the number of days of the week.

13.    Avoid using const on read-only variables. For that, use the readonly directive.

public class ReadOnlyVariables
{
public const int DaysInWeek = 7;

public readonly int Number;

public ReadOnlyVariables(int someValue)
{
Number = someValue;
}
}

14.    Catch only exceptions for which you have explicit handling.

15.    In a catch statement that throws an exception, always throw the original exception (or another exception constructed from the original exception) to maintain the stack location of the original error.

catch (OverflowException exception)
{
// Some handling.
throw;
}

16.    Avoid error codes as method return values.

17.    Avoid defining custom exception classes.

18.    When defining custom exceptions:

  • a.    Derive the custom exception from Exception. It was originally thought that custom exceptions should derive from ApplicationException. However in practice this has not been found to add significant value.
  • b.    Provide custom serialization.

19.    Do not put multiple Main() methods in a single assembly.

20.    Make only the most necessary types public. Mark others as internal.

21.    Do not write code that relies on an assembly running from a particular location.

22.    Minimize code in application assemblies (.exe client assemblies). Use class libraries instead to contain business logic.

23.    Avoid providing explicit values for enums unless they are integer powers of 2 and the enumeration is marked with the FlagsAttribute.

// Correct.
public enum CorrectColor
{
Red,
Green,
Blue
}

// Avoid.
public enum AvoidColor
{
None = 0,
Red = 1,
Green = 2,
Blue = 3
}

24.    Avoid specifying a type for an enum.

// Avoid.
public enum AvoidColorType : long
{
Red,
Green,
Blue
}

25.    Always use a curly brace scope in an if, while, do, for, foreach, lock and using statement, even if it contains a single statement.

26.    Avoid using the ternary conditional operator (?:).

27.    Avoid function calls in Boolean conditional statements. Assign into local variables and check on them.

public void AvoidThisMethod()
{
// Avoid.
if (IsEverythingOk())
{
}
}

public void UseThisMethod()
{
bool ok;

// Correct.
ok = IsEverythingOk();
if (ok)
{
}
}

28.    Always use zero-based arrays.

29.    With indexed collections, use zero-based indexes.

30.    Always explicitly initialize an array of reference types using a for loop.

31.    Do not provide public or protected member variables. Use properties instead.

32.    Avoid using the new inheritance qualifier. Use override instead.

33.    Never use unsafe code, except when using interop.

34.    Avoid explicit casting. Use the as operator to defensively cast to a type.

Dog dog;
GermanShepherd shepherd;

dog = new GermanShepherd(“Rin-Tin-Tin”);
shepherd = dog as GermanShepherd;
if (shepherd != null)
{
}

35.    Always check a delegate for null before invoking it.

36.    Avoid defining event-handling delegates. Use EventHandler<TEventArgs>.

37.    Avoid raising events explicitly. Use a protected virtual method to raise events. The name of the protected virtual method should be the same as the event name prefixed with On.

public event EventHandler Click;

private void SomeMethod()
{
OnClick(EventArgs.Empty);
}

protected virtual void OnClick(EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}

38.    Never hardcode strings that will be presented to end users. Use resources instead.

39.    Never hardcode strings that might change based on deployment such as connection strings.

40.    Use string.Empty instead of “”.

41.    When building a long string, use StringBuilder, not string.

42.    Avoid providing methods on structures.

  • a.    Parameterized constructors are encouraged.
  • b.    Can overload operators.

43.    Never use goto unless in a switch statement fall-through (goto case, goto default).

44.    Always have a default case in a switch statement. Throw an Exception when the default signals an error condition.

public void SampleSwitch()
{
int number;

number = SampleMethod();
switch (number)
{
case 1:
Trace.WriteLine(“Case 1”);
break;

case 2:
Trace.WriteLine(“Case 2”);
break;

default:
throw new FatalException(
Properties.Resources.SampleSwitchUnknownNumber + number);
}
}

45.    Do not use the this reference unless invoking another constructor from within a constructor.

46.    Do not use the base word to access base class members unless you wish to resolve a conflict with a subclasses member of the same name or when invoking a base class constructor.

// Example of proper use of ‘base’.
public class Dog
{
public Dog(string name)
{
}

public virtual void Bark(int seconds)
{
}
}

public class GermanShepherd : Dog
{
public GermanShepherd(string name)
: base(name)
{
}

public override void Bark(int seconds)
{
base.Bark(seconds);
}
}

47.    Implement Dispose() and Finalize() methods based on the template in the .NET Framework Developers Guide: Implementing a Dispose Method
http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx

48.    Always run code unchecked by default (for the sake of performance), but explicitly in checked mode for overflow- or underflow-prone operations.

49.    Avoid explicit code exclusion of method calls (#if … #endif). Use conditional methods instead.

[Conditional(“SampleCondition”)]
public void SampleMethod()
{
}

50.    Do not cast to and from System.Object in code that uses generics. Use constraints or the as operator instead.

public class SampleClass
{

}
// Correct.
public class CorrectClass<T> where T : SampleClass
{
void SampleMethod(T t)
{
SampleClass sample;

sample = t;
}
}

// Avoid.
public class AvoidClass<T>
{
void SampleMethod(T t)
{
object temp;
SampleClass sample;

temp = t;
sample = (SampleClass)temp;
}
}

51.    Do not define constraints in generic interfaces. Interface-level constraints can often be replaced by strong-typing.

public class Customer
{
}

// Correct.
public interface ICustomerList : IList<Customer>
{
}

// Avoid.
public interface IList<T> where T : Customer
{
}

52.    Do not define method-specific constraints in interfaces.

53.    Do not define constraints in delegates.

54.    If a class or a method offers both generic and non generic flavors, always prefer using the generics flavor.

55.    When implementing a generic interface that derives from an equivalent non-generic interface (such as IEnumerable<T>), use explicit interface implementation on all methods, and implement the non-generic methods by delegating to the generic ones.

public sealed class MyCollection<T> : IEnumerable<T>
{
private List<T> _store;

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _store.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
IEnumerable<T> enumerable = this;
return enumerable.GetEnumerator();
}
}

Hope these two posts were useful to you. These were like DotNet Coding guide for me always. Hoping it to be the same for you. Enjoy Reading.

.Net Coding Standards Part1 : Naming conventions and style


As .Net developers we tend to forget this key ingredient in our lives. Quite frequently, we end up in a coding mess. It would be good to take into account of coding standards before you start writing your first letter. It took me a lot to understand them. In no way you could learn them one shot. It takes time and experience. But never let it go off sight. Let me give you a hand out here.

Try to skim through it 3 – 5 times a day, for a week-like a medicine. It should get imprinted by then.

The following are some coding standards, i used to follow in my coding. Hope it would be useful to you all.

1.    When an identifier consists of multiple words, do not use separators such as underscores (_) between words. Instead use casing to indicate the beginning of each word.

2.    Use Pascal casing for type and method names and constants.

public class DataAccess
{
protected const string LastModifiedOn = “LastModifiedOn”;

public void CreateAdapter()
{
}
}

3.    Use camel casing for local variable names and method arguments.

public void StartTransaction(string environmentName)
{
DBConnection connection;
}

4.    Capitalize both characters of two-character acronyms, except the first word of a camel cased identifier.

5.    Capitalize only the first character of acronyms with three or more characters, except the first word of a camel cased identifier.

6.    Do not use abbreviations in identifiers. The two abbreviations that can be used in identifiers are ID and OK. In Pascal casing identifiers, they must appear as Id and Ok. If used as the first word in a camel cased identifier, they must appear as id and ok respectively.

7.    Prefix interface names with I.

public interface IBusinessFacade
{
void DeleteColumnLayout(ColumnLayoutInfo info);
}

8.    Prefix private member variables with an underscore (_). Use camel casing for the rest of a member variable name following the underscore (_).

public class DataAccessManager
{
private int _number;
}

9.    Suffix custom attribute classes with Attribute.

10.    Suffix custom exception classis with Exception.

11.    Name methods using verb-object pair, such as ShowDialog().

12.    Methods with return values should have a name describing the value returned, such as GetObjectState().

13.    Use descriptive variable names.

  • a.    Avoid single character variable names, such as i or t. Use index or temp instead.
  • b.    Do not use Hungarian notation.
  • c.    Do not abbreviate words (such as num instead of number).

14.    Always use language (C#) predefined types rather than the aliases in the System namespace.

object NOT Object
string NOT String
int    NOT Int32

15.    With generics, use capital letters for types. Reserve suffixing Type when dealing with the .NET type Type.

// Correct.
public class LinkedList<K, T>
{
}

// Not correct.
public class WrongLinkedList<KeyType, DataType>
{
}

16.    Use meaningful namespaces such as the product name or the company name. The general format for a namespace is as follows:

<Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]

17.    Avoid fully qualified type names. Use the using statement instead.

18.    Do not place a using statement inside a namespace.

19.    Group all framework namespaces together and put custom or third-party namespaces underneath.

using System;
using System.Collections.Generic;
using System.Text;

using Getronics.SampleLibrary;

20.    Use delegate inference instead of explicit delegate instantiation.

public delegate void TransactionalMethod();

private TransactionalMethod _method = Delete;

private static void Delete()
{
}

21.    Maintain strict indentation of 4 spaces (the default in Visual Studio 2005 Team Edition for Software Developers). Do not use tabs or nonstandard indentation, such as one space. The indentation should be uniform across all files.

22.    Indent comments at the same level of indentation as the code you are documenting.

23.    All comments use the English (US) language and should pass spell checking. Misspelled comments indicate sloppy development.

24.    All comments start with the single line comment characters //.

25.    All member variables of a class or structure must be declared at the top, with one line separating them from the properties or methods.

internal class DataAccessEnvironment
{
private DatabaseFactory _factory;
private long _baseValue;
private int _lowValue;

public DataAccessEnvironment()
{
}
}

26.    Declare local variables at the top of a block statement.

27.    A file name must reflect the class it contains.

28.    A class should use the following layout.

public class ClassLayout
{
#region Member variables
#endregion

#region Constructors
#endregion

#region Properties
#endregion

#region Methods
#endregion
}

29.    When using partial types and allocating a part per file, name each file after the logical part that part plays. For example:

// In file PartialClass.cs
public partial class PartialClass
{
}

// In file PartialClass.Designer.cs
public partial class PartialClass
{
}

30.    Always place an open curly brace ({) on a new line.

31.    With anonymous methods, mimic the code layout of a regular method, aligned with the anonymous delegate declaration (complies with placing an open curly brace on a new line).

public delegate void SampleMethod(string name);

public void InvokeMethod()
{
SampleMethod sampleMethod = delegate(string name)
{
MessageBox.Show(name);
};

sampleMethod(“Hello”);
}

32.    Use empty parentheses on parameter-less anonymous methods.

Also go through : .Net Coding Standards Part2 : Coding Practices