JS O N with C+ + & C#
JSON이란 Array형식으로 구조화된 데이터를 저장하는 형식으로써
XML과 비슷하다고 할 수 있다.
XML보다 크기가 작아서 네트워크로 송수신할 때 유리하다.
주로 웹서비스에서 많이 사용되었으나 최근 모바일 게임 등을 통해 게임에서도 사용되기 시작
JSON
<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
}
XML
DATA TYPE
Object
{ 로 시작해서 } 로 끝남
key – value 쌍으로 이루어진다.
key는 string만 가능
value는 object, string, number, array, true, false, null 이 가능
예 :
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
}
}
Array
흔히 알고 있는 배열과 같다고 할 수 있다.
[ 로 시작해서 ] 로 끝난다.
index를 통해서 접근하고, 저장되는 데이터의 타입은 서로 다를 수 있다.
value는 object, string, number, array, true, false, null 이 가능
예 :
[
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"},
5,
null,
“Hi”
]
String
문자열이고, 주의할 점은 “ ”로 감싸야 한다.
Number
int, float, real이 가능하다.
기타 자료형에는 true, false, null이 있다.
R A PIDJS O N
C++의 json 라이브러리
JSONKit, jsonme--, ThorsSerializer, JsonBox, jvar, jsoncpp, zoolib, JOST,
CAJUN, libjson, nosjob, rapidjson, jsoncons, JSON++, SuperEasyJSON, Casablanca
http://json.org/json-ko.html
rapidjson의 특징은 빠른 속도에 있으며 MIT License 이다.
공식 홈페이지는 아래와 같다.
https://code.google.com/p/rapidjson/
사용 법은 공식 홈페이지에서 소스를 받아 압축을 풀고,
includerapidjson 폴더 안의 document.h를 include함으로써 사용할 수 있다.
#include "rapidjson/document.h"
#include <cstdio>
int main() {
// 파싱할 문자열을 만든다.
const char json[] = "{ "hello" : "world" }";
// 파싱한 데이터를 관리할 document 객체 생성
rapidjson::Document d;
// 앞에서 만든 소스를 파싱해서 새로 생성한 객체에 그 결과를 담는다.
d.Parse<0>(json);
// 저장된 데이터에서 원하는 데이터를 접근해서 가져온다.
printf("%sn", d["hello"].GetString());
return 0;
}
// world가 출력된다.
>>> world
d.Parse<0>(json);
<0>은 파싱하는 옵션을 기본값으로 사용하겠다는 의미
d["hello"].GetString()
[ ]는 접근하려는 데이터의 d안에서의 위치
만약 [ ] 연산자 앞의 대상이 object라면 문자열(“ ” 형식의)을
이용해서 접근할 수 있고, array라면 index를 통해서 접근한다.
주의 할 점은 index로 접근할 때는 int를 바로 사용할 수는 없으며
rapidjson::SizeType으로 index를 캐스팅해주어야 한다.
예제 코드에서 d는 { }로 감싸진 object 이므로 문자열을 통해 접근
뒤의 .GetString()은 접근한 데이터를 어떤 타입으로 리턴할지 결정한다.
이외에도 GetInt(), GetInt64(), GetBool(), GetDouble() 등이 있다.
// JSON true나 false 모두 bool이므로 두 가지의 경우에는 true를 반환한다. IsTrue()도 가능하다.
assert( document["t"].IsBool() );
printf( "t = %sn", document["t"].GetBool() ? "true" : "false“ );
// numbe는 JSON type이므로 IsInt()로 좀 더 명확하게 알아볼 수 있다.
// 이 경우에는 IsUint() / IsInt64() / IsUInt64() 모두 true를 반환한다.
assert( document["i"].IsNumber() );
assert( document["i"].IsInt() );
// ( int )document[ “I” ]; 로 캐스팅도 가능하다.
printf( "i = %dn", document["i"].GetInt() );
// 접근한 데이터를 캐스팅 하지 않고, Value라는 자료형에 바로 담을 수도 있다.
const Value& a = document["a"];
assert( a.IsArray() );
// array의 데이터에 접근하는 index i는 SizeType이라는 자료형을 사용한다.
for ( SizeType i = 0; i < a.Size(); i++ )
printf( "a[%d] = %dn", i, a[i].GetInt() );
// 위의 예제에서 document["a"]라는 array 안의 특정 값만 필요하다면 다음과 같이 사용도 가능
// document["a"][SizeType(index)].GetInt();
rapidjson::Document document의
데이터가 다음과 같을 때
{
"hello": "world",
"t": true ,
"f": false,
"n": null,
"i": 123,
"pi": 3.1416,
"a": [
1,
2,
3,
4
]
}
오른쪽과 같은 작업을 할 수 있다.
#include "rapidjson/document.h“
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <cstdio>
...
/*
json data document를 string으로 변환
*/
// StringBuffer로 Writer를 만들어서 document에 등록
rapidjson::StringBuffer strbuf;
rapidjson::Writer<StringBuffer> writer(strbuf);
document.Accept(writer);
// StringBuffer에 .GetString()으로 변환된 string data를 얻을 수 있음
printf("--n%sn--n", strbuf.GetString());
return 0;
}
JS O N for .NE T
C#의 json 라이브러리
fastJSON, JSON_checker, Jayrock, Json.NET - LINQ to JSON, LitJSON, JSON for .NET,
JsonFx, JSON@CodeTitans, How do I write my own parser?, JSONSharp, JsonExSerializer,
fluent-json, Manatee Json, FastJsonParser
http://json.org/json-ko.html
JSON for .NET
http://csjson.sourceforge.net/
사용 법은 공식 홈페이지에서 소스를 받아 압축을 풀고,
System.Net.Json.dll을 Add Reference 해서 사용
using System;
using System.Collections.Generic;
using System.Text;
namespace Example
{
using System.Net.Json;
class Program
{
const string jsonText =
"{"+
" "FirstValue": 1.1,"+
" "SecondValue": "some text"," +
" "TrueValue": true" +
"}";
static void Main(string[] args)
{
// parser를 하나 만들어서 오브젝트에
// string data를 parser로 읽은 데이터를 저장
JsonTextParser parser = new JsonTextParser();
JsonObject obj = parser.Parse(jsonText);
// 이렇게 생성된 데이터는 현재 indentation을
// 포함한 상태이므로 이를 지우려면
JsonUtility.GenerateIndentedJsonText = false;
// json object의 값을 순회하면서 열거
foreach (JsonObject field in obj as JsonObjectCollection)
{
string name = field.Name;
string value = string.Empty;
string type = field.GetValue().GetType().Name;
// 출력을 위해 타입 확인 후, string으로 캐스팅
switch(type)
{
case "String":
value = (string)field.GetValue();
break;
case "Double":
value = field.GetValue().ToString();
break;
case "Boolean":
value = field.GetValue().ToString();
break;
default:
// 일단 arrays나 objects는 예외로 처리
throw new NotSupportedException();
}
Console.WriteLine("{0} {1} {2}",
name.PadLeft(15), type.PadLeft(10), value.PadLeft(15));
}
// JSON data 생성하기
// JsonObjectCollection을 하나 생성
JsonObjectCollection collection = new JsonObjectCollection();
// collection 사용하듯이 값을 추가
collection.Add(new JsonStringValue("FirstName", "Pavel"));
collection.Add(new JsonStringValue("LastName", "Lazureykis"));
collection.Add(new JsonNumericValue("Age", 23));
collection.Add(new JsonStringValue("Email", "me@somewhere.com"));
collection.Add(new JsonBooleanValue("HideEmail", true));
// indentation이 포함된 형태로 설정
JsonUtility.GenerateIndentedJsonText = true;
// string으로 바꿀 때는 아래와 같이
collection.ToString();
// FirstName을 얻으려면 “FirstName”이라는 키로 접근해서 값을 얻은 다음 캐스팅한다.
(String)collection[“FirstName"].GetValue();
http://jsonlint.com/
JSON 형태가 제대로 된 것인지 확인할 수 있는 사이트
참고자료
https://code.google.com/p/rapidjson/
http://www.json.org/
http://kimstar.pe.kr/blog/74

JSON with C++ & C#

  • 1.
    JS O Nwith C+ + & C#
  • 2.
    JSON이란 Array형식으로 구조화된데이터를 저장하는 형식으로써 XML과 비슷하다고 할 수 있다.
  • 3.
    XML보다 크기가 작아서네트워크로 송수신할 때 유리하다. 주로 웹서비스에서 많이 사용되었으나 최근 모바일 게임 등을 통해 게임에서도 사용되기 시작
  • 4.
    JSON <menu id="file" value="File"> <popup> <menuitemvalue="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup> </menu> { "menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } } XML
  • 5.
  • 6.
    Object { 로 시작해서} 로 끝남 key – value 쌍으로 이루어진다. key는 string만 가능 value는 object, string, number, array, true, false, null 이 가능 예 : { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021 } }
  • 7.
    Array 흔히 알고 있는배열과 같다고 할 수 있다. [ 로 시작해서 ] 로 끝난다. index를 통해서 접근하고, 저장되는 데이터의 타입은 서로 다를 수 있다. value는 object, string, number, array, true, false, null 이 가능 예 : [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}, 5, null, “Hi” ]
  • 8.
    String 문자열이고, 주의할 점은“ ”로 감싸야 한다. Number int, float, real이 가능하다. 기타 자료형에는 true, false, null이 있다.
  • 9.
  • 10.
    C++의 json 라이브러리 JSONKit,jsonme--, ThorsSerializer, JsonBox, jvar, jsoncpp, zoolib, JOST, CAJUN, libjson, nosjob, rapidjson, jsoncons, JSON++, SuperEasyJSON, Casablanca http://json.org/json-ko.html
  • 11.
    rapidjson의 특징은 빠른속도에 있으며 MIT License 이다. 공식 홈페이지는 아래와 같다. https://code.google.com/p/rapidjson/
  • 12.
    사용 법은 공식홈페이지에서 소스를 받아 압축을 풀고, includerapidjson 폴더 안의 document.h를 include함으로써 사용할 수 있다.
  • 13.
    #include "rapidjson/document.h" #include <cstdio> intmain() { // 파싱할 문자열을 만든다. const char json[] = "{ "hello" : "world" }"; // 파싱한 데이터를 관리할 document 객체 생성 rapidjson::Document d; // 앞에서 만든 소스를 파싱해서 새로 생성한 객체에 그 결과를 담는다. d.Parse<0>(json); // 저장된 데이터에서 원하는 데이터를 접근해서 가져온다. printf("%sn", d["hello"].GetString()); return 0; } // world가 출력된다. >>> world d.Parse<0>(json); <0>은 파싱하는 옵션을 기본값으로 사용하겠다는 의미 d["hello"].GetString() [ ]는 접근하려는 데이터의 d안에서의 위치 만약 [ ] 연산자 앞의 대상이 object라면 문자열(“ ” 형식의)을 이용해서 접근할 수 있고, array라면 index를 통해서 접근한다. 주의 할 점은 index로 접근할 때는 int를 바로 사용할 수는 없으며 rapidjson::SizeType으로 index를 캐스팅해주어야 한다. 예제 코드에서 d는 { }로 감싸진 object 이므로 문자열을 통해 접근 뒤의 .GetString()은 접근한 데이터를 어떤 타입으로 리턴할지 결정한다. 이외에도 GetInt(), GetInt64(), GetBool(), GetDouble() 등이 있다.
  • 14.
    // JSON true나false 모두 bool이므로 두 가지의 경우에는 true를 반환한다. IsTrue()도 가능하다. assert( document["t"].IsBool() ); printf( "t = %sn", document["t"].GetBool() ? "true" : "false“ ); // numbe는 JSON type이므로 IsInt()로 좀 더 명확하게 알아볼 수 있다. // 이 경우에는 IsUint() / IsInt64() / IsUInt64() 모두 true를 반환한다. assert( document["i"].IsNumber() ); assert( document["i"].IsInt() ); // ( int )document[ “I” ]; 로 캐스팅도 가능하다. printf( "i = %dn", document["i"].GetInt() ); // 접근한 데이터를 캐스팅 하지 않고, Value라는 자료형에 바로 담을 수도 있다. const Value& a = document["a"]; assert( a.IsArray() ); // array의 데이터에 접근하는 index i는 SizeType이라는 자료형을 사용한다. for ( SizeType i = 0; i < a.Size(); i++ ) printf( "a[%d] = %dn", i, a[i].GetInt() ); // 위의 예제에서 document["a"]라는 array 안의 특정 값만 필요하다면 다음과 같이 사용도 가능 // document["a"][SizeType(index)].GetInt(); rapidjson::Document document의 데이터가 다음과 같을 때 { "hello": "world", "t": true , "f": false, "n": null, "i": 123, "pi": 3.1416, "a": [ 1, 2, 3, 4 ] } 오른쪽과 같은 작업을 할 수 있다.
  • 15.
    #include "rapidjson/document.h“ #include "rapidjson/writer.h" #include"rapidjson/stringbuffer.h" #include <cstdio> ... /* json data document를 string으로 변환 */ // StringBuffer로 Writer를 만들어서 document에 등록 rapidjson::StringBuffer strbuf; rapidjson::Writer<StringBuffer> writer(strbuf); document.Accept(writer); // StringBuffer에 .GetString()으로 변환된 string data를 얻을 수 있음 printf("--n%sn--n", strbuf.GetString()); return 0; }
  • 16.
    JS O Nfor .NE T
  • 17.
    C#의 json 라이브러리 fastJSON,JSON_checker, Jayrock, Json.NET - LINQ to JSON, LitJSON, JSON for .NET, JsonFx, JSON@CodeTitans, How do I write my own parser?, JSONSharp, JsonExSerializer, fluent-json, Manatee Json, FastJsonParser http://json.org/json-ko.html
  • 18.
  • 19.
    사용 법은 공식홈페이지에서 소스를 받아 압축을 풀고, System.Net.Json.dll을 Add Reference 해서 사용
  • 20.
    using System; using System.Collections.Generic; usingSystem.Text; namespace Example { using System.Net.Json; class Program { const string jsonText = "{"+ " "FirstValue": 1.1,"+ " "SecondValue": "some text"," + " "TrueValue": true" + "}"; static void Main(string[] args) { // parser를 하나 만들어서 오브젝트에 // string data를 parser로 읽은 데이터를 저장 JsonTextParser parser = new JsonTextParser(); JsonObject obj = parser.Parse(jsonText); // 이렇게 생성된 데이터는 현재 indentation을 // 포함한 상태이므로 이를 지우려면 JsonUtility.GenerateIndentedJsonText = false; // json object의 값을 순회하면서 열거 foreach (JsonObject field in obj as JsonObjectCollection) { string name = field.Name; string value = string.Empty; string type = field.GetValue().GetType().Name; // 출력을 위해 타입 확인 후, string으로 캐스팅 switch(type) { case "String": value = (string)field.GetValue(); break; case "Double": value = field.GetValue().ToString(); break; case "Boolean": value = field.GetValue().ToString(); break; default: // 일단 arrays나 objects는 예외로 처리 throw new NotSupportedException(); } Console.WriteLine("{0} {1} {2}", name.PadLeft(15), type.PadLeft(10), value.PadLeft(15)); }
  • 21.
    // JSON data생성하기 // JsonObjectCollection을 하나 생성 JsonObjectCollection collection = new JsonObjectCollection(); // collection 사용하듯이 값을 추가 collection.Add(new JsonStringValue("FirstName", "Pavel")); collection.Add(new JsonStringValue("LastName", "Lazureykis")); collection.Add(new JsonNumericValue("Age", 23)); collection.Add(new JsonStringValue("Email", "me@somewhere.com")); collection.Add(new JsonBooleanValue("HideEmail", true)); // indentation이 포함된 형태로 설정 JsonUtility.GenerateIndentedJsonText = true; // string으로 바꿀 때는 아래와 같이 collection.ToString(); // FirstName을 얻으려면 “FirstName”이라는 키로 접근해서 값을 얻은 다음 캐스팅한다. (String)collection[“FirstName"].GetValue();
  • 22.
    http://jsonlint.com/ JSON 형태가 제대로된 것인지 확인할 수 있는 사이트
  • 23.