A simple JSON helper class

Source: Internet
Author: User

Paste a simple JSON helper class with the following code:

public class Jsonhelper
{
<summary>
Entity class to JSON
</summary>
<typeparam name= "T" ></typeparam>
<param name= "Jsonstring" ></param>
<returns></returns>
Public T jsonstringtoclass<t> (string jsonstring)
{
using (var ms = new MemoryStream (System.Text.Encoding.UTF8.GetBytes (jsonstring)))
{return (t) new DataContractJsonSerializer (typeof (T)). ReadObject (MS); }
}
<summary>
JSON to entity class
</summary>
<typeparam name= "T" ></typeparam>
<param name= "Jsonobject" ></param>
<returns></returns>
public string classtojsonstring<t> (T jsonobject)
{
using (var ms = new MemoryStream ())
{
New DataContractJsonSerializer (Jsonobject.gettype ()). WriteObject (MS, Jsonobject);
Return System.Text.Encoding.UTF8.GetString (Ms. ToArray ());
}
}
<summary>
JSON formatting
</summary>
<param name= "JSON" ></param>
<returns></returns>
public string Jsonformate (string json)
{
int level = 0;
var Jsonarr = json. ToArray ();
String jsontree = String. Empty;
for (int i = 0; i < JSON. Length; i++)
{
char C = jsonarr[i];
if (Level > 0 && ' \ n ' = = Jsontree.toarray () [jsontree.length-1])
{
Jsontree + = Treelevel (level);
}
Switch (c)
{
Case ' {':
Jsontree + = "\ r \ n" +C;
Break
Case '} ':
Jsontree + = "\ r \ n" +C;
Break
Case ' [':
Jsontree + = c + "\ r \ n";
level++;
Break
Case ', ':
Jsontree + = c + "\ r \ n";
Break
Case '] ':
Jsontree + = "\ r \ n";
level--;
Jsontree + = Treelevel (level);
Jsontree+=c;
Break
Default
Jsontree + = C;
Break
}
}
return jsontree;
}
string treelevel (int level)
{
String leaf = string. Empty;
for (int t = 0, T < level; t++)
{
leaf + = "\ T";
}
return leaf;
}
<summary>
JSON file formatting
</summary>
<param name= "filepath" ></param>
<returns></returns>
public string Jsonfileformatte (string filepath)
{
Try
{
if (! File.exists (filepath))
{
Return "The incoming file does not exist!" ";
}
String str = File.readalltext (filepath);
str = jsonformate (str);
File.writealltext (filepath, str);
Return "Operation was successful! ";
}catch (Exception ex)
{
Return ex. Message;
}
}
<summary>
JSON into entity class
</summary>
<param name= "JSON" ></param>
<returns></returns>
Public dynamic Convertjsontodynamic (string json)
{
JavaScriptSerializer JSS = new JavaScriptSerializer ();
Jss. Registerconverters (new javascriptconverter[] {new Dynamicjsonconverter ()});
Dynamic dy = JSS. Deserialize (JSON, typeof (object)) as dynamic;
return dy;

}
}

Class Dynamicjsonconverter:javascriptconverter
{
public override object Deserialize (idictionary<string, object> dictionary, type type, JavaScriptSerializer Serializer)
{
if (dictionary = = null)
throw new ArgumentNullException ("dictionary");

if (type = = typeof (object))
{
return new Dynamicjsonobject (dictionary);
}

            return null;
       }

        public override idictionary<string, object> Serialize (Object obj , JavaScriptSerializer Serializer)
        {
             throw new NotImplementedException ();
       }
        public override ienumerable<type> Supportedtypes
         {
            get {return new readonlycollection<type> (new list<type> (new type[] {typeof (Object)}));
       }
   }
    class Dynamicjsonobject:dynamicobject
    {
         private idictionary<string, object> Dictionary {get; set;}

Public Dynamicjsonobject (idictionary<string, object> dictionary)
{
This. Dictionary = Dictionary;
}

public override bool Trygetmember (GetMemberBinder binder, out object result)
{
result = this. Dictionary[binder. Name];

If (result is idictionary<string, object>)
{
result = new Dynamicjsonobject (result as idictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is idictionary<string, object>)
{
result = new List<dynamicjsonobject> ((result as ArrayList). ToArray (). Select (x = new Dynamicjsonobject (x as idictionary<string, object>));
}
else if (result is ArrayList)
{
result = new List<object> ((result as ArrayList). ToArray ());
}

return this. Dictionary.containskey (binder. Name);
}
}

A simple JSON helper class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.