posted by 방랑군 2012. 1. 4. 04:32
출처 :

http://weblogs.asp.net/navaidakhtar/archive/2008/07/08/converting-data-table-dataset-into-json-string.aspx

 

Converting Data Table / Dataset Into JSON String

JSON (Java Script Object Notation), is a light weight, easily understandable to read and write string. It is also easily parse-able by machine.

JSON is introduced on two structues

A collection (key/value pair)

And ordered list of values.

I have not covered this topic in detail. Detailed analysis is stated on http://www.json.org/.

I am presenting a helper function (in C#) fordevelopers for fast parsing on datatable / dataset into JSON String,and access it on client-side.

public static string GetJSONString(DataTable Dt)

{

string[] StrDc = new string[Dt.Columns.Count];

string HeadStr = string.Empty;

for (int i = 0; i < Dt.Columns.Count; i++)

{

StrDc[i] = Dt.Columns[i].Caption;

HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";

}

HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

StringBuilder Sb = new StringBuilder();

Sb.Append("{\"" + Dt.TableName + "\" : [");

for (int i = 0; i < Dt.Rows.Count; i++)

{

string TempStr = HeadStr;

Sb.Append("{");

for (int j = 0; j < Dt.Columns.Count; j++)

{

TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());

}

Sb.Append(TempStr + "},");

}

Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));

Sb.Append("]};");

return Sb.ToString();

}

Here, Dt is the datatable, and it returns JSON formatted string.

For detailed porcedure on how to access this string on client side, please refer to this link Exposing Webservices to Client-Side because I don't like to do task repetition.

Please donot forget to convert to JSON string to JSON Object using

var JObject = eval('(' + JSONString + ')');

in Javascript JObject have all characteristics of JSON object, through which you can Use JObject by iterrating or what so ever.

e.g., you can use your JObject as

for(var i = 0; i < JObject .Employees.length; i++)

{

var val1 = JObject.Employees[i].EmployeeID;

var val2 = JObject.Employees[i].NationalIDNumber;

var val3 = JObject.Employees[i].Title;

var val4 = JObject.Employees[i].BirthDate;

var val5 = JObject .Employees[i].HireDate ;

}

Please note that I am querieng data from AdventurWorksDB SQL Sample Database (Table: Employee).

I hope this article will be helpful for you.

Any Questions / Queries ??

Regards,

Naveed Akhtar




'PP > JSON' 카테고리의 다른 글

JSON 의 eval() 함수 사용의 문제  (0) 2012.01.09
JSON Text를 JSON Object로 변환하기  (0) 2012.01.09
Json / JQuery (Ajax)/ Asp.net 3가지를 연동하여 데이터 가져오기  (0) 2012.01.07
JSON 개요 및 예제  (0) 2012.01.04
JSON.NET  (0) 2012.01.04
posted by 방랑군 2012. 1. 4. 04:30
http://json.codeplex.com/

 
DataSet <-> Json 파일

최근 이슈가 되고 있는 Json(Javascript Object Notation)은 텍스트 타입의 데이터 처리 방식에 있어서 XML을 대체할 만한 또 다른 형태이다.

장점이라면 XML DOM 호출에 비해 처리 속도가 뛰어나며, Cross-site Domian에서도 사용이 가능하다.

 

현재 관리하고 있는 사이트를 좀 더 가볍게 하기 위해 기존 XML이나 DataSet의 형태를 Json으로 작업하기 위해 관련 자료를 찾아보던 중

Codeplex에서 소개하고 있는 Json.NET framework을 사용해 보았다...

 

        public string Serialize(object value)
        {
            Type type = value.GetType();

            JsonSerializer json = new JsonSerializer();

            json.NullValueHandling = NullValueHandling.Ignore;

            json.ObjectCreationHandling = ObjectCreationHandling.Replace;
            json.MissingMemberHandling = MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

 

            if (type == typeof(DataRow))
                json.Converters.Add(new DataRowConverter());
            else if (type == typeof(DataTable))
                json.Converters.Add(new DataTableConverter());
            else if (type == typeof(DataSet))
                json.Converters.Add(new DataSetConverter());

 

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            if (this.FormatJsonOutput)
                writer.Formatting = Formatting.Indented;
            else
                writer.Formatting = Formatting.None;

 

            writer.QuoteChar = '"';
            json.Serialize(writer, value);

 

            string output = sw.ToString();
            writer.Close();
            sw.Close();

 

            return output;
        }

        public object Deserialize(string jsonText, Type valueType)
        {
            JsonSerializer json = new JsonSerializer();

 

            json.NullValueHandling = NullValueHandling.Ignore;
            json.ObjectCreationHandling = ObjectCreationHandling.Replace;
            json.MissingMemberHandling = MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

 

            StringReader sr = new StringReader(jsonText);
            JsonTextReader reader = new JsonTextReader(sr);
            object result = json.Deserialize(reader, valueType);
            reader.Close();

 

            return result;
        }

 

 

위 두개의 Method는 테이터 타입의 정보를 Json 형태로 변환이 가능하다.

예로 DataSet의 데이터를 Json으로 변환해 보자..

 public void SetJson()

{

    string JsonFileNM = "Test_JsonFile.jsf";

    string JsonString = string.Empty;

    DataSet ds =  null;

 

    ds = Test.GetData(...);

    JsonString = Serialize(ds);

     ....

     //*******************//

     // JsonFileNM로 파일 저장  //

     //*******************//

 ...

}

 

public DataSet GetJson(Sstring jsonText)

{

    DataSet ds = (DataSet)Deserialize(jsonText, typeof(DataSet)));

    return ds;

}

 

Json.NET framework의 특징은 다음과 같다.

-Flexible JSON serializer to convert .NET objects to JSON and back again
-LINQ to JSON for reading and writing JSON
-Writes indented, easy to read JSON
-Convert JSON to and from XML
-Supports Silverlight and Windows Phone

 

CodePlex에서 관련 소스를 download가 가능하다.

http://json.codeplex.com/

http://www.west-wind.com/Weblog/posts/471835.aspx