±à¼ÍƼö: |
±¾ÎÄÖ÷Òª½éÉÜÁËÈçºÎ°ÑDataTableתΪJSON
string¡¢ÈçºÎÐòÁл¯£¿ÈçºÎ´ÓtxtÎļþÖжÁÈ¡JSON¸ñʽµÄÊý¾Ý²¢·´ÐòÁл¯£¿×ܽáÒÔ¼°ÈçºÎÒÆÖ²µ½webºÍÆäËûÐòÁл¯Í¾¾¶µÈÏà¹Ø¡£
±¾ÎÄÀ´×ÔÓÚcsdn£¬ÓÉ»ðÁú¹ûAnna±à¼ÍƼö |
|
1.Ìù³öÖ÷ÎļþµÄËùÓдúÂë
¸Ã°¸ÀýÎÒÊÇÓÃWinForm×öµÄ£¬ÏàÐŴ󲿷ÖÈ˶¼ÊÇÔÚWeb¿ª·¢ÖÐÓã¬Õâ¸öû¹ØÏµ¡£
Ê×ÏÈÄãÐèÒª¸øÄãµÄProjectÒýÈëËùÐèµÄdll¡£System.WebºÍSystem.Web.ExtensionsÈçͼ

ºÃµÄ£¬ÏÂÃæÊÇÎÒÓóÌÐò´´½¨µÄÒ»¸öJSON ¸ñʽµÄÃûΪ¡±json.txt¡±µÄÎı¾¡£
[{"name":"Jason","id":
"20130001","phone":"13579246810"}, {"name":"Alias","id":
"20130002","phone":"18437965529"}, {"name":"Tom","id":
"20130003","phone":"15090246296"}] |
ÏÂÃæÊÇÎÒµÄWinFormµÄUIºÍʶ±ð´úÂëÂ߼Ч¹û

ÈçºÎÄã½âÎöµÄJSON²»ÊǶà¸ö¶ÔÏ󣬶øÊÇÒ»¸ö£¬È磺
{"name":"Jason","id":"20130001",
"phone":"13579246810"}
|
ÄÇôִÐÐЧ¹ûÈçͼ£º

ºÃµÄ£¬×÷Ϊ¸¨Öú£¬ÎÒ´´½¨ÁËÒ»¸öclass Person£¬´úÂëÈçÏ£º
public class
Person
{
private string _name;
private int _id;
private string _phone; public string Phone
{
get { return _phone; }
set { _phone = value; }
} public int Id
{
get { return _id; }
set { _id = value; }
} public string Name
{
get { return _name; }
set { _name = value; }
} public Person() { }
public Person(int id, string name, string phone)
{
this._id = id;
this._name = name;
this._phone = phone;
} } |
È»ºó¾ÍÊÇÖ÷Âß¼´úÂ룺ÈçÏ£¬
/*
* Author : Áõ׳
* Edit Date : 2016/5/1
* Email :
* Description: 1.Create a txt file with json
string.
* 2.Deserialize JSON string by two ways.
* 3.You can type a json with object or a json
array.
*/
using System;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections; namespace _02_·´ÐòÁл¯ºÍ·´ÐòÁл¯
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string filename = "json.txt";
JavaScriptSerializer jss = new JavaScriptSerializer(); /// <summary>
/// ´´½¨Ò»¸ö´øÓÐjson¸ñʽµÄtxt
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateJson_Click(object sender,
EventArgs e)
{
//Create a new document with json string. //Judge whether the specified file exists.
if (!File.Exists(filename))
{
//MessageBox.Show("no existence");
//File.Create(filename);
//Write a json string into the specified file
using (StreamWriter sw = new StreamWriter(filename,
false, System.Text.Encoding.UTF8))
{
//ÏÂÃæÍ¨¹ýÒ»¸öÀý×ÓÑÝʾÁËÈçºÎ´ÓjsonתΪDataTable£¬ÔÙÓÉDataTableתΪJSON
string.
string json = string.Empty;
json = "[{\"name\":\"Jason\",
\"id\":20130001, \"phone\":\"13579246810\"},"
+
"{\"name\":\"Alias\",
\"id\":20130002, \"phone\":\"18437965529\"},"
+
"{\"name\":\"Tom\",
\"id\":20130003, \"phone\":\"15090246296\"}]"; DataTable dt = new DataTable();
//json = ToJson (new Person(20130001,"Json","12345678901"));
dt = JsonToDataTable(json);
json = DataTableToJson(dt);
sw.Write(json);
}
MessageBox.Show ("the specified have been
created!");
}
else
{
MessageBox.Show ("the file was existing.you
can delete it then re click it.");
}
} /// <summary>
/// Reading the specified file that contains
a json string
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAnalyzeJson_Click(object sender,
EventArgs e)
{
//Judge whether the specified file exists.
if (File.Exists(filename))
{
//Getting the string that is a specified file
using (StreamReader sr = new StreamReader(filename,
System.Text.Encoding.UTF8))
{
string json = sr.ReadToEnd();
//analyze the json string.
txtOrgJson.Text = json;
//The first method.(For one object)
//Person p = jss.Deserialize(json,typeof(Person))
as Person;
//txtAnalysedJson.Text = "name="+p.Name+"\r\nid="+
p.Id+"\r\nphone="+p.Phone; //The second method.(For a lots objects)
List<Person> people = jss.Deserialize<List<Person>>(json);
StringBuilder sb = new StringBuilder();
PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance
| BindingFlags.NonPublic | BindingFlags.Public);
if (people.Count == 0)
{
DeserializeToObject(json);
return;
} //Get the name and value of the specified
class Person automatically.
foreach (var person in people)
{
sb.Clear();
foreach (PropertyInfo pi in piArr)
{
sb.Append(pi.Name + "=" + pi.GetValue(person));
sb.Append("\t ");
}
listAll.Items.Add(sb.ToString());
//listAll.Items.Add("name=" + person.Name
+ "\tid=" + person.Id + "\tphone="
+ person.Phone);
}
}
}
else
{
MessageBox.Show ("Cannot find the specified
file.Please click the up button of this.");
}
} /// <summary>
/// Converts the specified JSON string to a
object of type T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
private T Deserialize<T>(string jsonString)
{
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Deserialize<T>(jsonString);
} private void btnDelFile_Click (object sender,
EventArgs e)
{
if (File.Exists(filename))
{
File.Delete(filename);
MessageBox.Show("Deleted");
}
} /// <summary>
/// Convert JSON string to Object
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConvert_Click (object sender,
EventArgs e)
{
string json = txtOrgJson.Text.Trim();
if (!String.IsNullOrEmpty(json))
{
List<Person> lPerson = Deserialize <List<Person>>(json); StringBuilder sb = new StringBuilder();
PropertyInfo[] piArr = typeof(Person).GetProperties
(BindingFlags.Instance | BindingFlags.NonPublic
| BindingFlags.Public);
if (lPerson.Count == 0)
{
DeserializeToObject(json);
return;
} //Get the name and value of the specified
class Person automatically.
foreach (var person in lPerson)
{
sb.Clear();
foreach (PropertyInfo pi in piArr)
{
sb.Append(pi.Name + "=" + pi.GetValue(person));
sb.Append("\t ");
}
listAll.Items.Add(sb.ToString());
} }
} /// <summary>
/// Clear the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClear_Click (object sender,
EventArgs e)
{
listAll.Items.Clear();
} private void DeserializeToObject (string data)
{
Person p = jss.Deserialize (data, typeof(Person))
as Person;
txtAnalysedJson.Text = "name= " + p.Name
+ "\r\nid=" + p.Id + "\r\nphone="
+ p.Phone;
} /// <summary>
/// ConvertS an object to a JSON string
/// </summary>
/// <param name="o">Object</param>
/// <returns></returns>
private string ToJson(Object o)
{
JavaScriptSerializer j = new JavaScriptSerializer();
return j.Serialize(o);
} /// <summary>
/// ConvertS an object to a JSON string When
the string length is long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
private string ToJson2(Object o)
{
JavaScriptSerializer j = new JavaScriptSerializer();
j.MaxJsonLength = Int32.MaxValue;
return j.Serialize(o);
} /// <summary>
/// Converts datatable to JSON string.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private string DataTableToJson(DataTable dt)
{
JavaScriptSerializer javaScriptSerializer =
new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
//È¡µÃ×î´óÊýÖµ
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dictionary
= new Dictionary<string, object>(); //ʵÀý»¯Ò»¸ö²ÎÊý¼¯ºÏ
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add (dataColumn.ColumnName, dataRow
[dataColumn.ColumnName].ToString());
}
arrayList.Add(dictionary); //ArrayList¼¯ºÏÖÐÌí¼Ó¼üÖµ
} return javaScriptSerializer.Serialize(arrayList);
//·µ»ØÒ»¸öjson×Ö·û´®
}
/// <summary>
/// Json ×Ö·û´® ת»»Îª DataTableÊý¾Ý¼¯ºÏ
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public DataTable JsonToDataTable (string json)
{
DataTable dataTable = new DataTable(); //ʵÀý»¯
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer =
new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
//È¡µÃ×î´óÊýÖµ
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary
in arrayList)
{
if (dictionary.Keys.Count == 0)
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add (current, dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
} dataTable.Rows.Add(dataRow); //Ñ»·Ìí¼ÓÐе½DataTableÖÐ
}
}
}
catch
{
}
result = dataTable;
return result;
}
}
} |
ÉÏÃæÓõ½Á˺ܶ෽·¨£¬¶¼ÊǺÜÖØÒªºÜÖØÒªºÜÖØÒªµÄ£¬ÖØÒªÊÇÊÂÇéҪ˵Èý±é£¡£¡£¡ÓÉÓÚʹÓõÄWinForm¿ª·¢µÄ£¬ËùÒÔÉÏÃæµÄ´úÂëÖлẬÓв¿·Ö¿Ø¼þµÄName¡£
ÏÂÃæÎÒ½«»á·Ö¿ª²¿·Ö½²Ò»Ï¸ð¸ÀýµÄºËÐÄ·½·¨
2.Öð¸ö·ÖÎöÖ®ÈçºÎ°ÑJSON string תΪDataTable
1.Ê×ÏÈ´´½¨Ò»¸öJsonToDataTableµÄͨÓ÷½·¨
/// <summary>
/// Json ×Ö·û´® ת»»Îª DataTableÊý¾Ý¼¯ºÏ
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public DataTable JsonToDataTable(string json)
{
DataTable dataTable = new DataTable(); //ʵÀý»¯
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer =
new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
//È¡µÃ×î´óÊýÖµ
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary
in arrayList)
{
if (dictionary.Keys.Count == 0)
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
} dataTable.Rows.Add(dataRow); //Ñ»·Ìí¼ÓÐе½DataTableÖÐ
}
}
}
catch
{
}
result = dataTable;
return result;
} |
2.н¨Ò»¸öjson×Ö·û´®²¢¸³Öµ¡£È»ºóµ÷ÓÃÉÏÃæµÄ·½·¨¾Í¿ÉÒÔתΪDataTableÁË¡£
string json
= string.Empty;
json = "[{\"name\":\"Jason\",\"id\":20130001,
\"phone\":\"13579246810\"},"
+
"{\"name\":\"Alias\",
\"id\":20130002, \"phone\":\"18437965529\"},"
+
"{\"name\":\"Tom\",\"id\":
20130003,\"phone\":\"15090246296\"}]";
DataTable dt = JsonToDataTable(json);
|
3.ÈçºÎ°ÑDataTableתΪJSON string
1.н¨Ò»¸öDataTableToJsonµÄ·½·¨
/// <summary>
/// Converts datatable to JSON string.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private string DataTableToJson(DataTable dt)
{
JavaScriptSerializer javaScriptSerializer =
new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue;
//È¡µÃ×î´óÊýÖµ
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dictionary
= new Dictionary<string, object>(); //ʵÀý»¯Ò»¸ö²ÎÊý¼¯ºÏ
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add (dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
}
arrayList.Add(dictionary); //ArrayList¼¯ºÏÖÐÌí¼Ó¼üÖµ
} return javaScriptSerializer.Serialize(arrayList);
//·µ»ØÒ»¸öjson×Ö·û´®
} |
2.µ÷Ó÷½·¨£¬´«ÈëÒ»¸öDataTable¾Í¿ÉÒÔ¡£ÄĸöDataTable¶¼¿ÉÒԵġ£
string json
= DataTableToJson(dt);
|
4.ÈçºÎÐòÁл¯£¿
1.´´½¨Ò»¸ö·½·¨
/// <summary>
/// ConvertS an object to a JSON string When
the string length is long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
private string ToJson2(Object o)
{
JavaScriptSerializer j = new JavaScriptSerializer();
j.MaxJsonLength = Int32.MaxValue;
return j.Serialize(o);
} |
2.¾ÍÕâÑù´«ÈëÒ»¸ö¶ÔÏó¾ÍÐÐÁË¡£
±ÈÈ磺Person p = new Person();string json = ToJson2(p);
ÉÏÃæÔÚDataTableÖÐÒ²Óõ½¹ýÐòÁл¯µÄDemo£¬¿ÉÒԲο¼Óõ½´óÁ¿Êý¾Ýʱ½øÐÐתJSON
5.ÈçºÎ´ÓtxtÎļþÖжÁÈ¡JSON¸ñʽµÄÊý¾Ý²¢·´ÐòÁл¯
¼òÊöÏÂÁ÷³Ì£º
1.ÅжÏtxtµÄ´æÔÚ
2.¶ÁÈ¡txtµÄÄÚÈÝ
3.ͨ¹ýÏÂÃæµÄ´úÂë°ÑJSON¶ÔÏó´æÈëÒ»¸ö·ºÐÍÖÐ
List<Person>
people = jss.Deserialize<List<Person>>(json); |
4.ͨ¹ýÓ³É䣬×Ô¶¯»ñÈ¡µ½JSON¶ÔÓ¦Àà(Class)µÄÊôÐÔÃû£¬ÊµÏÖ×Ô¶¯»¯²¢Í¨¹ý±éÀúÊä³ö
PropertyInfo[]
piArr = typeof(Person).GetProperties (BindingFlags.Instance
| BindingFlags.NonPublic | BindingFlags.Public);
if (people.Count == 0)
{
DeserializeToObject(json);
return;
} //Get the name and value of the specified
class Person automatically.
foreach (var person in people)
{
sb.Clear();
foreach (PropertyInfo pi in piArr)
{
sb.Append(pi.Name + "=" + pi.GetValue(person));
sb.Append("\t ");
}
listAll.Items.Add(sb.ToString());
//listAll.Items.Add ("name=" + person.Name
+ "\tid=" + person.Id + "\tphone="
+ person.Phone);
} |
ÏÂÃæÊÇÓõ½µÄ·½·¨
/// <summary>
/// Reading the specified file that contains
a json string
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAnalyzeJson_Click(object sender,
EventArgs e)
{
//Judge whether the specified file exists.
if (File.Exists(filename))
{
//Getting the string that is a specified file
using (StreamReader sr = new StreamReader(filename,
System.Text.Encoding.UTF8))
{
string json = sr.ReadToEnd();
//analyze the json string.
txtOrgJson.Text = json;
//The first method.(For one object)
//Person p = jss.Deserialize (json,typeof(Person))
as Person;
//txtAnalysedJson.Text = "name= "+p.Name+"\r\nid="+p.Id+"\r\nphone="+p.Phone; //The second method.( For a lots objects)
List<Person> people = jss.Deserialize<List<Person>>(json);
StringBuilder sb = new StringBuilder();
PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance
| BindingFlags.NonPublic | BindingFlags.Public);
if (people.Count == 0)
{
DeserializeToObject(json);
return;
} //Get the name and value of the specified
class Person automatically.
foreach (var person in people)
{
sb.Clear();
foreach (PropertyInfo pi in piArr)
{
sb.Append(pi.Name + "=" + pi.GetValue(person));
sb.Append("\t ");
}
listAll.Items.Add(sb.ToString());
//listAll.Items.Add("name=" + person.Name
+ "\tid=" + person.Id + "\tphone="
+ person.Phone);
}
}
}
else
{
MessageBox.Show("Cannot find the specified
file.Please click the up button of this.");
}
} |
6.×ܽáÒÔ¼°ÈçºÎÒÆÖ²µ½webºÍÆäËûÐòÁл¯Í¾¾¶
ÏÈдÕâô¶à£¬ÄãÓÐʲôÒÉÎÊÒ²¿ÉÒÔÁôÑÔ½»Á÷һϣ¬¸Ã°¸Àý½ö¹©²Î¿¼£¬²»´ú±í±ê×¼°¸Àý¡£ÁíÍ⣬ÓÉÓÚÕâÀïÓõÄÊÇWinForm¿ª·¢£¬ÄãÔÚWebÀïͨ¹ýPOST·½·¨´«ÈëjsonÊý¾Ýʱ£¬¿ÉÄÜÐèҪͨ¹ýÏÂÃæµÄ·½·¨»ñÈ¡µ½json
string
StreamReader reader
= new StreamReader (context.Request.InputStream);
//±ÈÈçµÃµ½json×Ö·û´®£ºstrJson={"key3":"xdp-gacl","key4":"°×»Ê"}
String strJson = HttpUtility.UrlDecode (reader.ReadToEnd());
|
È»ºóÏÂÃæ¾ÍÊǰ´ÉÏÃæµÄ°¸ÀýÖеķ½·¨½øÐÐÓÅ»¯£¬µ÷Õû¡£
ÁíÍâÄØ£¬Èç¹ûÊÇ´«ÈëµÄJSON stringÊÇÒ»¸ö£¬ÄÇô¿ÉÒÔͨ¹ý¼üÖµ¶ÔµÄ·½Ê½À´¶ÁÈ¡£º
/// <summary>
/// »ñÈ¡²ÎÊý
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private System.Collections.Generic.Dictionary<String,
Object> GetParameter(HttpContext context)
{
StreamReader reader = new StreamReader(context.Request.InputStream);
//µÃµ½json×Ö·û´®£ºstrJson= {"key3":"xdp-gacl","key4":"°×»¢Éñ»Ê"}
String strJson = HttpUtility.UrlDecode (reader.ReadToEnd());
System.Web.Script.Serialization .JavaScriptSerializer
jss = new System.Web.Script.Serialization .JavaScriptSerializer();
//½«json×Ö·û´®·´ÐòÁл¯³ÉÒ»¸öDictionary¶ÔÏó
System.Collections.Generic .Dictionary<String,
Object> dicParameter = jss.Deserialize<
System.Collections.Generic.Dictionary <String,
Object>>(strJson);
return dicParameter;
} |
µ÷Ó÷½Ê½
Dictionary<String,
Object> dicParameter = GetParameter(context);
string key3 = dicParameter["keyword"].ToString(); |
ÁíÍâÄØ£¬³ýÁËÉÏÃæµÄÐòÁл¯Ö®Í⣬»¹¿ÉÒÔÓÃÏÂÃæµÄ·½·¨£º
public static string
ToJsJson(object item)
{
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(item.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, item);
StringBuilder sb = new StringBuilder("");
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
return sb.ToString();
}
} |
ÐèÒªÄãÒýÓãºusing System.Runtime.Serialization.Json; |