Contents

Views 58536 Comment 0
Atachment
Attachment '4'
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print

참고 : http://bit.ly/eY2Jyh (여기와 같은 내용의 dll을 업로드 함.)


XML 과 더불어 Open Protocol 로 많이 쓰이는 것이 JSon 입니다.


아래는 wiki 에서 긁어온 정의 입니다.


JSON(제이슨, JavaScript Object Notation)은, 인터넷에서 자료를 주고받을 때 그 자료를 표현하는 방법이다. 자료의 종류에 큰 제한은 없으며, 특히 컴퓨터 프로그램의 변수값을 표현하는 데 적합하다.

그 형식은 자바스크립트의 구문 형식을 따르지만, 프로그래밍 언어나 플랫폼에 독립적이므로 C, C++, 자바, 자바스크립트, 펄, 파이썬 등 많은 언어에서 이용할 수 있다.

RFC 4627로 규격화되었다.


JSON 문법은 자바스크립트 표준인 ECMA-262 3판의 객체 문법에 바탕을 두며, 인코딩은 유니코드로 한다. 표현할 수 있는 자료형에는 수, 문자열, 참/거짓이 있고, 또 배열과 객체도 표현할 수 있다.

배열은 대괄호로 나타낸다. 배열의 각 요소는 기본자료형이거나 배열, 객체이다.

[10, {"v": 20}, [30, "마흔"]]


객체는 이름/값 쌍의 집합으로, 중괄호로 싼다. 이름은 문자열이기 때문에 반드시 따옴표를 하며, 값은 기본자료형이거나 배열, 객체이다. 각 쌍이 나오는 순서는 의미가 없다.

{"name2": 50, "name3": "값3", "name1": true}

{
   "이름": "테스트",
   "나이": 25,
   "성별": "여",
   "기혼": true,
   "주소": "서울특별시 양천구 목동",
   "특기": ["농구", "도술"],
   "가족관계": {"#": 2, "아버지": "홍판서", "어머니": "춘섬"}
   "회사": "경기 안양시 만안구 안양7동"
}


다양한 Wrapper 함수들이 많이 존재하고 있는데 대표적으로 System.Net.Json.dll import 를 이용한 데이터 생성 방법 및 파싱 방법에 대해 간단한 예제로 정리를 해보았습니다.


우선 import 를 해야겠죠?


1> 아래 이미지와 같이 특정 위치의 파일을 import 하시면 다음과 같은 wrapper 헤더를 보실 수 있습니다.

1_elastica.jpg


//JSonObject 관련 헤더

using System;
using System.Collections.Generic;
using System.Reflection;

namespace System.Net.Json
{
  public class JsonObjectCollection : JsonCollection
  {
    public JsonObjectCollection();
    public JsonObjectCollection(IEnumerable<JsonObject> collection);
    public JsonObjectCollection(string name);
    public JsonObjectCollection(string name,
        IEnumerable<JsonObject> collection);

    protected override char BeginCollection
    {
      get;
    }
    
    protected override char EndCollection
    {
      get;
    }
    
    public JsonObject this[string name]
    {
      get;
    }
  }
}



//JSon 배열 객체 관련 헤더

using System;
using System.Collections.Generic;

namespace System.Net.Json
{
  public class JsonArrayCollection : JsonCollection
  {
    public JsonArrayCollection();
    public JsonArrayCollection(IEnumerable<JsonObject> collection);
    public JsonArrayCollection(string name);
    public JsonArrayCollection(string name,
        IEnumerable<JsonObject> collection);
    
    protected override char BeginCollection
    {
      get;
    }
    
    protected override char EndCollection
    {
      get;
    }
  }
}



2> 데이터 생성 방법

샘플로 다음과 같은 데이터를 생성해 보겠습니다.

res {
    "name": "john", 
    "tellist": [  "1234",  "4321",  "1111" ], 
    "moreinfo": 
    {
        "age": "10",  "sex": "male",  "city": "seoul"
    }
} 


john 이라는 사람의 신상정보로써 전화번호는 1234,4321,1111 세가지가 있으며,

부가 정보로 나이,성별,거주지 정보를 가지고 있습니다.


위 데이터를 라이브러리를 통해 생성해 보겠습니다.

using System.Net.Json;

//john 이라는 value 를 가진 name object 생성
JsonObjectCollection res = new JsonObjectCollection();
res.Add(new JsonStringValue("name", "john"));
                                    
//tellist 배열 생성
JsonArrayCollection items = new JsonArrayCollection("tellist");
items.Add(new JsonStringValue(null, "1234"));
items.Add(new JsonStringValue(null, "4321"));
items.Add(new JsonStringValue(null, "1111"));
res.Add(items);
                       

//부가정보 objectCollection 생성
JsonObjectCollection moreinfo = new JsonObjectCollection();
moreinfo.Add(new JsonStringValue("age", "10"));
moreinfo.Add(new JsonStringValue("sex", "male"));
moreinfo.Add(new JsonStringValue("city", "seoul"));

//res Collection 에 추가
JsonObjectCollection ressub =
    new JsonObjectCollection("moreinfo", moreinfo);

res.Add(ressub);



아래 이미지에서 정상적으로 생성이 되었음을 확인할 수 있습니다.

2_elastica.jpg



3>실제 데이터 가져오는 방법

root 노드에서의 데이타를 쉽게 가져오기 위해 다음과 같은 함수 두개를 추가합니다.

즉 제일 상위 레벨에서 객체의 값이나 배열의 값을 가지고 오기 위한 함수입니다.

(GetStringValue, GetStringArrayValue)


//JSon 파서

public class JSONParser
{
  private JsonTextParser parser;
  private JsonObjectCollection col;

  public JSONParser(string strData)
  {
    parser = new JsonTextParser();
    col = (JsonObjectCollection)parser.Parse(strData);
  }
  
  /**
  * (확장)JsonObjectCollection.GetStringValue(string name)
  * param name: 찾을 엘리먼트의 이름
  * return: 엘리먼트의 값
  */
  public string GetStringValue(string name)
  {
    try
    {
      return (string)col[name].GetValue();
    }
    catch
    {
      return null;
    }
  }
  
  /**
  * (확장)JsonObjectCollection.GetStringArrayValue(string name)
  * param name: 찾을 엘리먼트의 이름
  * return: 엘리먼트의 배열값
  */
  public string[] GetStringArrayValue(string name)
  {
    try
    {
      JsonArrayCollection items = (JsonArrayCollection)col[name];
      string[] item = new string[items.Count];
      
      for (int count = 0; count < items.Count; count++)
        item[count] = ((JsonStringValue)items[count]).Value;

      if (item.Length == 0)
      {
        return null;
      }
      else
      {
        return item;
      }
    }
    catch
    {
      return null;
    }
  }

  /**
  * (확장)JsonObjectCollection.Remove(string name)
  * param name: 삭제할 엘리먼트의 이름
  */
  public void Remove(string name)
  {
    try
    {
      JsonObject obj = col[name];
      col.Remove(obj);
    }
    catch
    {
    }
  }
}


JSONParser myParser = new JSONParser(payload);

//배열 tellist 정보를 가지고 옴
string[] telarray = myParser.GetStringArrayValue("tellist");
int intlength = telarray.Length;
  
//name 의 value 를 가지고 옵니다.
string namevalue = myParser.GetStringValue("name");

string value,name;

JsonTextParser parser = new JsonTextParser();
JsonObject obj = parser.Parse(payload);
  
  
//moreinfo 객체는 root 가 아니라 sub 객체로 구성되어 있으므로 처리가 필요합니다.
foreach (JsonObject field in obj as JsonObjectCollection)
{
  name = field.Name;
  value = string.Empty;

  if (name == "moreinfo")
  {
    //즉 value 값을 다시 JsonObjcet 로 변환해줌
    JsonObject objSub = (JsonObject)(field);

    //moreinfo 객체의 값들을 가지고 옵니다 age,sex,city  
    foreach (JsonObject fieldSub in objSub as JsonObjectCollection)
    {
      name = fieldSub.Name;
      value = (string)fieldSub.GetValue();
        
      if (name == "age") 
      {
      }
      else if (name == "sex")
      {
      }
      else if (name == "city")
      {
      }
    }
  }
}

4_elastica.jpg


?

List of Articles
No. Category Subject Author Date Views
1161 Develop GCM 사용하기 3 (JSP로 GCM 푸시 서버 만들기) 4 file hooni 2013.07.06 25315
1160 Develop git 브런치 배우기 (링크) hooni 2013.07.09 20571
1159 Develop GPL, AGPL, MPL,.. 한눈에 보는 오픈소스SW 라이선스 file hooni 2014.10.14 1146
1158 Etc GSM에서 음성이 실리는 과정 요약.. hooni 2013.04.23 17518
1157 Etc How to completely Uninstall Coda hooni 2017.10.24 2149
1156 System/OS How to Install and Use wget on Mac file hooni 2020.09.03 1277
1155 System/OS How to Setup an Email Server on CentOS 7 hooni 2018.04.05 2779
1154 Develop How to Test SMTP AUTH using Telnet hooni 2018.04.05 1332
1153 System/OS HTTP 프로토콜 (브라우저와 웹서버 간의 통신) hooni 2003.04.23 48250
1152 System/OS HTTPS와 SSL 인증서 file hooni 2014.03.11 7546
1151 Etc iOS 에서 쓸만한 오프라인 구글지도 찾기 hooni 2014.01.06 16035
1150 Etc IoT가 만드는 미래와 플랫폼 경쟁력 secret hooni 2014.09.23 0
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 98 Next
/ 98