Delphi / Lazarus / C ++ビルダーのシンプルで小さなクラスの高速JSON解析。
いくつかの関心点:
McJSON )、1つのクラス( TMcJsonItem )のみです。 uses
McJSON;
...
function Test99 (out Msg: string): Boolean;
var
Json: TMcJsonItem;
i: Integer;
begin
Msg := ' Test: Github readme.md content ' ;
Json := TMcJsonItem.Create();
try
try
// add some pairs.
Json.Add( ' key1 ' ).AsInteger := 1 ;
Json.Add( ' key2 ' ).AsBoolean := True;
Json.Add( ' key3 ' ).AsNumber := 1.234 ;
Json.Add( ' key4 ' ).AsString := ' value 1 ' ;
// add an array
Json.Add( ' array ' , jitArray);
for i := 1 to 3 do
Json[ ' array ' ].Add.AsInteger := i;
// save a backup to file
if (Json[ ' array ' ].Count = 3 ) then
Json.SaveToFile( ' test99.json ' );
// remove an item
Json.Delete( ' array ' );
// oops, load the backup
if (Json.Count = 4 ) then
Json.LoadFromFile( ' test99.json ' );
// test final result
Result := (Json.AsJSON = ' {"key1":1,"key2":true,"key3":1.234,"key4":"value 1","array":[1,2,3]} ' );
except
Result := False;
end ;
finally
Json.Free;
end ;
end ; testtest99.jsonを生成します:
{
"key1" : 1 ,
"key2" : true ,
"key3" : 1.234 ,
"key4" : " value 1 " ,
"array" : [
1 ,
2 ,
3
]
}# include " McJson.hpp "
...
bool Test99 (AnsiString& Msg)
{
bool Result;
TMcJsonItem* Json = NULL ;
Msg = " Test: Github readme.md content " ;
Json = new TMcJsonItem ();
try
{
try
{ // add some pairs.
Json-> Add ( " key1 " )-> AsInteger = 1 ;
Json-> Add ( " key2 " )-> AsBoolean = true ;
Json-> Add ( " key3 " )-> AsNumber = 1.234 ;
Json-> Add ( " key4 " )-> AsString = " value 1 " ;
// add an array
Json-> Add ( " array " , jitArray);
for ( int i = 1 ; i <= 3 ; i++)
Json-> Values [ " array " ]-> Add ()-> AsInteger = i;
// save a backup to file
if (Json-> Values [ " array " ]-> Count == 3 )
Json-> SaveToFile ( " test99.json " );
// remove an item
Json-> Delete ( " array " );
// oops, load the backup
if (Json-> Count == 4 )
Json-> LoadFromFile ( " test99.json " );
// test final result
Result = (Json-> AsJSON ==
" { " key1 " :1, " key2 " :true, " key3 " :1.234, " key4 " : " value 1 " , " array " :[1,2,3]} " );
}
catch (...)
{
Result = false ;
}
}
__finally
{
if (Json) delete (Json);
}
return (Result);
}McJSONユースケースの完全なリストについては、 testフォルダーで単位テストを読んでください。
AsJSONプロパティを使用するだけです
var
N: TMcJsonItem;
begin
N := TMcJsonItem.Create;
N.AsJSON := ' {"i": 123, "f": 123.456, "s": "abc", "b": true, "n": null} ' ;
// use N here
N.Free;
end ; JSON文字列が有効かどうかを確認する場合:
Answer := N.Check( ' {"i":[123} ' ); // Answer will be false Check方法は例外を提起しません。上記の例はError while parsing text: "expected , got }" at pos "10"例外をキャッチして管理する必要がある場合は、次のようなCheckExceptionを使用します。
try
Answer := N.CheckException( ' {"k":1, "k":2} ' ); // Answer will be false
except
on E: Exception do
begin
// Error while parsing text: "duplicated key k" at pos "11"
end ;
end ; McJSON 、パスを介してアイテムにアクセスする簡単な方法を可能にします。 '/'、 ''、または 'を使用できます。パスセパレーターとして。
N.AsJSON := ' {"o": {"k1":"v1", "k2":"v2"}} ' ;
// access and change second object's value
N.Path( ' o.k2 ' ).AsString := ' value2 ' ;結果:
{
"o" : {
"k1" : " v1 " ,
"k2" : " value2 "
}
}このように、 Path()インデックスをまだ受け入れていないことに注意してください。
N.AsJSON := ' {"o": [{"k1":"v1"}, {"k2":"v2"}] ' ;
N.Path( ' o[1].k2 ' ).AsString := ' value2 ' ;バージョン1.0.4であるため、 McJSON Andreas HausladenのJSONデータオブジェクトのようなプロパティショーナーを使用できます。
// access (automatic creation as in JDO)
Obj.S[ ' foo ' ] := ' bar ' ;
Obj.S[ ' bar ' ] := ' foo ' ;
// array creation, Obj is the owner of 'array'
Obj.A[ ' array ' ].Add.AsInteger := 10 ;
Obj.A[ ' array ' ].Add.AsInteger := 20 ;
// object creation, 'array' is the owner of ChildObj
ChildObj := Obj[ ' array ' ].Add(jitObject);
ChildObj.D[ ' value ' ] := 12.3 ;
// array creation, ChildObj is the owner of 'subarray'
ChildObj.A[ ' subarray ' ].Add.AsInteger := 100 ;
ChildObj.A[ ' subarray ' ].Add.AsInteger := 200 ;結果:
{
"foo" : " bar " ,
"bar" : " foo " ,
"array" :[
10 ,
20 ,
{
"value" : 12.3 ,
"subarray" :[
100 ,
200
]
}
]
}JSONオブジェクトのすべてのアイテム(子供)にアクセスし、その値の種類とコンテンツを変更する方法は次のとおりです。
N.AsJSON := ' {"o": {"k1":"v1", "k2":"v2"}} ' ;
// type and value: from string to integer
for i := 0 to N[ ' o ' ].Count- 1 do
N[ ' o ' ].Items[i].AsInteger := i+ 1 ; 結果:
{
"o" : {
"k1" : 1 ,
"k2" : 2
}
}Items[index]とValues['key']プロパティを使用して、オブジェクトと配列内のアイテムにアクセスできます。バージョン0.9.5以降、 At(index, 'key')またはAt('key', index)短縮剤として使用できます。
N.AsJSON := ' {"a": [{"k1":1,"k2":2},{"k1":10,"k2":20}]} ' ;
// how to access k2 of second object.
i := N[ ' a ' ].Items[ 1 ].Values[ ' k2 ' ].AsInteger; // i will be equal to 20
i := N[ ' a ' ].Items[ 1 ][ ' k2 ' ].AsInteger; // uses the Values[] as default property
i := N[ ' a ' ].At( 1 , ' k2 ' ).AsInteger; // shortener: index, key
i := N.At( ' a ' , 1 )[ ' k2 ' ].AsInteger; // shortener: key, indexまた、 keyパラメーターがない他の用途があります。
N.AsJSON := ' {"k1":1,"k2":2,"k3":3,"k4":4} ' ;
i := N.Items[ 2 ].AsInteger; // i will be equal to 3
i := N.At( 2 ).AsInteger; // shortener: just index
i := N.At( ' k3 ' ).AsInteger; // shortener: just keyDelphi Enumeratorを使用すると、アイテムのオブジェクトの子供と価値を閲覧できます。
var
N, item: TMcJsonItem;
begin
N := TMcJsonItem.Create;
N.AsJSON := ' {"o": {"k1":"v1", "k2":"v2"}} ' ;
for item in N[ ' o ' ] do
// use item here, e.g. item.Key, item.Value, item.AsString複数のアイテムを持つオブジェクトのすべての値を変更します。あまり一般的ではありません。
N.AsJSON := ' {"o": {"k1":"v1", "k2":"v2"}} ' ;
N[ ' o ' ].AsString := ' str ' ;結果:
{
"o" : {
"k1" : " str " ,
"k2" : " str "
}
}そして、 oのタイプを変更する必要がある場合:
N[ ' o ' ].ItemType := jitValue;
N[ ' o ' ].AsString := ' str ' ;結果:
{
"o" : " str "
}アレイからオブジェクトタイプに変換し、その逆。また、あまり一般的ではありません。
N.AsJSON := ' { "k1": ["1", "2"], "k2": {"1": "a", "2": "b"} } ' ;
N[ ' k1 ' ].ItemType := jitObject; // convert array to object with items
N[ ' k2 ' ].ItemType := jitArray ; // convert object with items to array 結果:
{
"k1" : {
"0" : " 1 " ,
"1" : " 2 "
},
"k2" : [
" a " ,
" b "
]
}キーと位置を使用していくつかのアイテムを挿入します。
P.Insert( ' c ' , 0 ).AsInteger := 3 ;
P.Insert( ' b ' , 0 ).AsInteger := 2 ;
P.Insert( ' a ' , 0 ).AsInteger := 1 ;結果:
{
"a" : 1 ,
"b" : 2 ,
"c" : 3
}また、配列にオブジェクトを挿入することも可能です。
Q.AsJSON := ' {"x":0} ' ;
P.ItemType := jitArray;
P.Insert(Q, 1 );結果:
[
1 ,
{
"x" : 0
},
2 ,
3
]重要:バージョン0.9.3であるため、 Add()およびInsert()は、タイプTMcJsonItemの引数をクローンします。したがって、 Qのメモリも解放する必要があります。
P.Free;
Q.Free;バージョン1.0.5の文字列はMcJsonEscapeString()ヘルパー関数で逃げることができるため:
N.AsJSON := ' {"path": ' + McJsonEscapeString( ' dirsubdir ' ) + ' } ' ; 結果:
{
"path" : " \ dir \ subdir "
}バージョン1.0.6では、これらのエスケープレベルでMcJsonEscapeString()で使用されるTJEscapeType enumを導入しました。
jetNormal :脱出#8 #9 #10 #12 #13 " 。jetStrict :通常 + / 。jetUnicode :strict + uXXXX 。jetNone :後方互換性。これらのレベルは、ライブラリFPJSONのLazarusのヘルパー関数StringToJSONString()に触発されています。
TMcJsonItemオブジェクトのすべての内部データ構造、タイプ、および値を検査する方法を見てみましょう。
// ---------------------------------------------------------------------------
void
TFormMain::Inspect (TMcJsonItem* AMcJItem, AnsiString Ident)
{
if (!AMcJItem) return ;
// log current
MyLog ( Ident + ItemToStr (AMcJItem) );
// log child
if ( AMcJItem-> HasChild )
{
Ident = " " + Ident;
for ( int i= 0 ; i < AMcJItem-> Count ; i++)
{ // use Value not Child because are note using Key[].
Inspect ( AMcJItem-> Items [i], Ident );
}
}
}
// ---------------------------------------------------------------------------
String
TFormMain::ItemToStr (TMcJsonItem* AMcJItem) const
{
String Ans = " " ;
if (AMcJItem)
Ans = AMcJItem-> GetTypeStr () +
" ; " + AMcJItem-> GetValueStr () +
" ; Key= " + AMcJItem-> Key +
" ; Value= " + AMcJItem-> Value +
" ; JSON= " + AMcJItem-> AsJSON ;
return (Ans);
}
// ---------------------------------------------------------------------------そして、 testInspect.jsonのような例を使用してください:
{
"foo" : " bar " ,
"array" : [
100 ,
20
],
"arrayObj" : [
{
"key1" : 1.0
},
{
"key2" : 2.0
}
],
"Msg" : [
" #1 UTF8 example: motivação " ,
" #2 Scapes: btnfr\ uFFFF "\ "
]
} testInspect.jsonをロードしたJsonオブジェクトを使用してInspect()を呼び出します:
TMcJsonItem* Json = new TMcJsonItem();
if (Json)
{
Json-> LoadFromFile ( " testInspect.json " );
Inspect (Json);
delete (Json);
}結果:
object; string; Key=; Value=; JSON={"foo":"bar","array":[100,20],"arrayObj":[{"key1":1.0},{"key2":2.0}],"Msg":["#1 UTF8 example: motivação","#2 Scapes: btnfru"\"]}
value; string; Key=foo; Value=bar; JSON="foo":"bar"
array; string; Key=array; Value=; JSON="array":[100,20]
value; number; Key=; Value=100; JSON=100
value; number; Key=; Value=20; JSON=20
array; string; Key=arrayObj; Value=; JSON="arrayObj":[{"key1":1.0},{"key2":2.0}]
object; string; Key=; Value=; JSON={"key1":1.0}
value; number; Key=key1; Value=1.0; JSON="key1":1.0
object; string; Key=; Value=; JSON={"key2":2.0}
value; number; Key=key2; Value=2.0; JSON="key2":2.0
array; string; Key=Msg; Value=; JSON="Msg":["#1 UTF8 example: motivação","#2 Scapes: btnfruFFFF"\"]
value; string; Key=; Value=#1 UTF8 example: motivação; JSON="#1 UTF8 example: motivação"
value; string; Key=; Value=#2 Scapes: btnfruFFFF"\; JSON="#2 Scapes: btnfruFFFF"\"
バージョン0.9.0以降、空のキーは解析され、エラーが確認されます。
N.AsJSON := ' {"": "value"} ' ; ToString()は有効なJSONオブジェクトを生成します。
{
"" : " value "
}内部的には、FKEYフィールドのコンテンツとしてC_EMPTY_KEY定数文字列を使用します。
バージョン0.9.2以降、逃げられないラインブレークを持つ文字列にはエラーが解析されます。
N.AsJSON := ' {"key": "value ' + # 13 + ' "} ' ;例外を提起します:
Error while parsing text: "line break" at pos "14"
McJSON 、ASCIIおよびUTF-8ファイルから(BOMの有無にかかわらず)ロードできます。 LoadFromFileメソッドを参照してください。 SaveToFileメソッドは、UTF-8エンコーディングを使用して書き込みます。注:Vertion 1.0.4以降、LazarusのテストプロジェクトのソースコードはUTF-8に変換されたため、 asUTF8パラメーターはfalseに設定されました。
世界は完璧ではなく、どちらも私もいません。ここにいくつかの既知の問題があります:
TMcJsonItemオブジェクトは、リストfChildを使用して階層構造にインスタンス化されるため、アイテム間で自動的に伝播するフィールドを作成する問題があります。調査中のソリューションは、オブジェクトがルーツのようになり、子供としてTMcJsonItemオブジェクトを持つ新しい親クラスTMcJsonを作成しようとします。元のmyJSON 、 LkJson 、 JsonTools 、 uJSONユニットでパフォーマンステストが行われました。これがテストの概要です。
{... {"keyi":"valuei"}... }そして、使用されるコンパイラとマシンについて:
次の表は、結果1を要約しています。
| 図書館 | 生成する | 保存 | 解析 | 負荷 | アクセス | 合計 |
|---|---|---|---|---|---|---|
McJSON 2 | .11 s | .07 s | .12 s | .09 s | .83 s | 1.25秒 |
LkJson 2 | .30 s | .11 s | .47 s | .36 s | .01 s | 1.24 s |
JsonTools | 48.00秒 | .70 s | 39.00 s | 40.00秒 | .48 s | 1.2分 |
myJSON | 50.00 s | .07 s | 5.1分 | 7.7分 | 1.60秒 | 13.1分 |
uJSON | 18.6分 | 20.1分 | 17.5分 | 4.31 s | 53.02 s | 57.6分 |
McJSONについてのメモJson->Add("key")->AsString = "value" 。JsonP->AsJSON = Json->AsJSON使用して解析します。LkJsonについてのメモTlkBalTreeにより、ランダムアクセスを使用して、優れたパフォーマンス生成と解析、さらに優れています。dynamic_castコードverbosyを作成する必要があります。Json->Add("key", "value") 。JsonP = dynamic_cast<TlkJSONObject*>(TlkJSON::ParseText(NULL, TlkJSON::GenerateText(NULL, Json))) 。JsonToolsについてのメモJson->Add("key", "value") 。JsonP->Value = Json->AsJson使用して解析します。myJSONについてのメモJson->Item["key"]->setStr("value") 。JsonP->Code = Json->getJSON()使用して解析します。uJSONについてのメモLkJsonよりもC ++では冗長性が少ないが、クラスの収集により、 dynamic_castでキャストを強制することもできます。uJSONでは、 toString()に関連するパフォーマンスの問題があるようです。Json->put("key", "value") 。JsonP = new TJSONObject(Json->toString())使用して解析します。SaveToFile存在しないため、 Json->toString()でTextに記入した後TStringList->SaveToFile()を使用しました。 メトリック:5回連続の実行の平均秒時間。合計は部分テストの平均です。いくつかの結果は議事録(分)に変換されました。 ↩
バージョン1.0.5。改善されたJSON 0.9.0プロジェクトは、まもなくリリースされます。 ↩2