JSON은 써보면 써볼수록 유용한 것 같다. 간결하고 편하고 직관적이다. 어쨌든 JSON Text를 Object로 변환해야 할 때가 있다. 여기서 JSON Text라는 것은 형태는 JSON의 형태이지만 자바스크립트에서 이걸 Object가 아닌 그냥 텍스트로만 인식하고 있다는 것이다. 이걸 Object로 바꾸어야만 그안의 값을 불러다가 사용할 수 있다.
가장 흔한 예가 Ajax를 사용할 경우이다. Ajax로 호출을 하고 결과값으로 받은 req.responseText로 JSON을 받았을 경우에는 그냥 Text이기 때문에 Object로 변환해 주어야 한다.
JSON.parse()의 목적대로 JSON 텍스트 외에는 거부해야하기 때문에 JSON문법을 정확히 지켜주지 않으면 SyntaxError 예외가 던져진다. 그렇기 때문에 키와 값을 모두 쌍따옴표(")로 묶어주는 문법을 정확하게 지켜주어야 한다.(물론 이 경우는 값들이 스트링이기 때문에 쌍따옴표로 묶어주는 것입니다.) 아래처럼....
{ "id":"outsider", "sex":"male" }
여기서 JSON.parse()를 사용하기 위해서는 Douglas Crockford가 만든 json2.js가 필요하다. json2.js는 더글라스 크록포드가 JSON의 편리한 사용을 위해 만든 JSON API의 새버전이다.(그래서 2가 붙어있다.) 이 API에는 2개의 메서드가 들어있는데 JSON.stringify()와 JSON.parse()이다. JSON.stringify()는 JSON.parse()와는 완전히 반대로 JSON 객체를 주면 JSON 텍스트로 만들어서 준다. 필요할때 갖다 쓰면 된다. (John Resig이 이전버전보다 새버전의 API가 훨씬 좋다고 꼭 이걸 쓰란다.)
휠자가 하려고 했던 것은 다음과 같다.
1. ActiveX에서 마우스 클릭 시
이벤트를 ClientScript에 통지!!
2. 통지 받으면 Ajax로 서버딴에 DB질의를 요청
3.
서버쪽에서는 웹서비스로 DB에 질의 요청 후 받은 데이터를 JSON으로 변환 4. 기다리고 있던
ClientScript에서는 JSON으로 질의에 대한 응답을 받음
현재 설명하려고 하는 내용은 Ajax로 서버딴에
DB질의 요청 및 받은 데이터를 JSON으로 변환하는 것이에용
namespace
ICSService
{
public class DataSetConverter :
JavaScriptConverter
{
public override IEnumerable<Type>
SupportedTypes
{
//Define the DataTable as a supported
type.
get { return new ReadOnlyCollection<Type>(new
List<Type>(new Type[] { typeof(DataSet) })); }
}
public override IDictionary<string, object> Serialize(object obj,
JavaScriptSerializer serializer)
{
Dictionary<string, object> dtDic = new Dictionary<string,
object>();
DataSet ds = obj as DataSet;
foreach
(DataTable dt in ds.Tables)
{
// Create the
representation.
Dictionary<string, object> rowDic = new
Dictionary<string, object>();
int i =
0;
foreach (DataRow row in dt.Rows)
{
//Add each entry to the
dictionary.
Dictionary<string, object> colDic = new
Dictionary<string, object>();
foreach (DataColumn
col in row.Table.Columns)
{
colDic.Add(col.ColumnName, row[col]);
}
rowDic.Add("row" + (i++).ToString(),
colDic);
}
dtDic.Add(dt.TableName,
rowDic);
}
return dtDic;
}
public override object Deserialize(IDictionary<string, object> dictionary,
Type type, JavaScriptSerializer serializer)
{
if
(dictionary == null)
throw new
ArgumentNullException("dictionary");
if (type ==
typeof(DataTable))
{
// Create the instance to
deserialize into.
DataTable list = new
DataTable();
// Deserialize the ListItemCollection's
items.
ArrayList itemsList =
(ArrayList)dictionary["Rows"];
for (int i = 0; i <
itemsList.Count; i++)
list.Rows.Add(serializer.ConvertToType<DataRow>(itemsList[i]));
return list;
}
return null;
}
}
}
DataSetConverter 클래스의
사용
[WebMethod]
public string
SelectPresetByCameraCode_Web(string[] CameraCode)
{
DataSet ds = (DataSet)XmlHelper.ExcuteXml(Server.MapPath(PRESET_XML),
"SelectPresetByCameraCode_Web", CameraCode);
JavaScriptSerializer
jss = new JavaScriptSerializer();
DataSetConverter dsc = new
DataSetConverter();
IDictionary<string, object> retVal =
dsc.Serialize(ds, jss);
string result =
jss.Serialize(retVal);
return result;
}
1) JSON : JavaScript Object Notation 2) lightweight data 교환 형식. 3) 사람이 읽고 쓰기 쉬움. 4) 기계가 파싱하고 생성하기 쉬움.
2. 일반사항
1) The official Internet media type for JSON : application/json 2) 확장자 : .json 3) Structured dat를 네트워크 상에서 주고 받을때 주로 사용 (주로 Ajax 등에서) 4) subset of Javascript : specifically, Standard ECMA-262 3rd Edition?December 1999 6) json.org : JSON 바인딩에 대한 다양한 자료 제공 7) Yahoo / Google : JSON 지원
3. 특징
1) JavaScript의 Array 문법으로 데이터 구조를 기술하는 방법으로 XML이 가지는 유연성과 구조적 데이터 표현기능을 확보하면서, XML이 가진 오버헤드를 줄이는 방법으로 사용되고 있다. 2) 클라이언트에서는 JavaScript의 eval()로 객체로 만들어 사용, 별도의 파싱 절차가 필요없음 (클라이언트에서 처리 퍼포먼스 높음) 3) 서버측 JSON 파싱 모듈은 거의 모든 언어별로 지원(Java, C, ActionScript, Delphi, Ruby, Perl, CAMAL등) 4) 클라이언트/서버측 모두 송신은 문자열 조립으로 처리 5) XML이 표현하는 구조적인 정보 모두 표현가능 6) 송수신 데이터로 XML를 사용하는 것에 비해 훨씬 빠르고, 간편하다. 7) language-independent text format, 대부분의 브라우저, 언어에서 지원된다. 8) 주로 XmlHttp 로 script text를 수신하여 다음과 같은 코드로 객체로 build 한다. (예제 : myObject = eval("return " + json_data); )
4. 데이타 타입
1) Object - 중괄호({})로 시작하고 끝남 - member : 문자열과 값으로 구성되어 있고 콜론( 으로 구분, 각 멤버들은 콤마(,)로 구분 - value : 값은 object, string, number, array, true, false, null 사용 가능
2) String - 문자열은 쌍따옴표(")로 둘러 쌓여야 함 - Unicode character 또는 일반적인 escape 문자(\", \\, \/, \b, \f, \n, \r, \t, \u four-hex-digits)를 포함한다.
3) Number - integer, real or floating point
4) Array - an ordered sequence of values - 대괄호([])로 시작하고 끝나며 각 값은 콤마(,)로 구분
5) true 6) false 7) null
5. 예제 #1
1) 사람을 나타내는 JSON 예제
2) 설명 - 성,이름,주소,전화라는 각 object는 Key:Value로 구성 - 각 Object는 ,로 구분 - 이름의 Value는 String - 주소의 Value는 Object - 전화의 Value는 배열
3) 사용법 - var p = eval('(' + contact + ')'); - p.firstName, p.address.city, p.phoneNumbers[0]
6. 예제 #2
1) 그림을 나타내는 JSON 예제
2) 설명 - 출처 : rfc4627 - 예제에서 Image는 최상위 object이고 모든 다른 데이터들은 이 object의 멤버. - Width, Height, Title는 숫자와 문자열 데이타를 포함하고 있는 기본적인 멤버. - Thumbnail은 Url, Height, Width를 멤버로 포함하고 있는 중첩 object. - IDs는 숫자 값을 가지고 있는 array. - Url 문자열 값에서 슬래쉬 가 escape 됨에 주의
7. 예제 #3
1) 메뉴를 나타내는 JSON 예제
2) 위와 동일한 XML
8. PHP
1) 5.2버전부터 json_encode 함수 지원 2) 서버에서 JSON 포멧으로 리턴하는 예제
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).
StringReader sr = new StringReader(jsonText); JsonTextReader reader = new JsonTextReader(sr); object result = json.Deserialize(reader, valueType);
reader.Close();
-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