Reference: http://www.cnblogs.com/shenshi/archive/2009/05/19/1460466.html
1. Add system reference
// Add reference to system. Web. Extensions. dll in vs2005
Using system. Web;
Using system. Web. Script. serialization;
Using system. Data;
Using system. collections;
2. Detailed code
/// <Summary>
/// Summary of jsonhelper
/// </Summary>
Public class jsonhelper
{
// Corresponding JSON singleinfo Member
Public String singleinfo = string. empty;
Protected string _ error = string. empty;
Protected bool _ success = true;
Protected long _ totalcount = 0;
Protected system. Collections. arraylist arrdata = new arraylist ();
Protected system. Collections. arraylist arrdataitem = new arraylist ();
Public jsonhelper ()
{
}
// Success member corresponding to JSON
Public bool success
{
Get
{
Return _ success;
}
Set
{
// Clear error if set to true
If (SUCCESS) _ error = string. empty;
_ Success = value;
}
}
// Error member corresponding to JSON
Public String Error
{
Get
{
Return _ error;
}
Set
{
// If an error is set, success is set to false automatically.
If (value! = "") _ Success = false;
_ Error = value;
}
}
Public long totlalcount
{
Get {return _ totalcount ;}
Set {_ totalcount = value ;}
}
// Reset. This method must be executed every time a new JSON object is generated.
Public void reset ()
{
_ Success = true;
_ Error = string. empty;
Singleinfo = string. empty;
Arrdata. Clear ();
Arrdataitem. Clear ();
}
Public void additem (string name, string value)
{
Arrdata. Add ("/" "+ name +"/":" + "/" "+ value + "/"");
}
Public void itemok ()
{
Arrdata. Add ("<br> ");
Totlalcount ++;
}
// Serialize the JSON object to obtain the returned JSON code
Public override string tostring ()
{
Stringbuilder sb = new stringbuilder ();
SB. append ("{");
SB. append ("totalcount:" + totlalcount. tostring () + ",");
SB. append ("success:" + _ success. tostring (). tolower () + ",");
SB. append ("error:/" "+ _ error. Replace ("/"", "//" ") + "/",");
SB. append ("singleinfo:/" "+ singleinfo. Replace ("/"", "//") + "/",");
SB. append ("data :[");
Int Index = 0;
SB. append ("{");
If (arrdata. Count <= 0)
{
SB. append ("}]");
}
Else
{
Foreach (string Val in arrdata)
{
Index ++;
If (Val! = "<Br> ")
{
SB. append (Val + ",");
}
Else
{
SB = sb. Replace (",", "", SB. Length-1, 1 );
SB. append ("},");
If (index <arrdata. Count)
{
SB. append ("{");
}
}
}
SB = sb. Replace (",", "", SB. Length-1, 1 );
SB. append ("]");
}
SB. append ("}");
Return sb. tostring ();
}
}