Delphi / Lazarus / C ++建造者简单而小型班级,用于快速解析。
一些兴趣点:
McJSON ),只有一个类( 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);
}请考虑在test文件夹中读取单元测试,以获取McJSON用例的完整列表。
只需使用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 key使用Delphi 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;由于McJsonEscapeString()助手函数可以逃脱1.0.5版。
N.AsJSON := ' {"path": ' + McJsonEscapeString( ' dirsubdir ' ) + ' } ' ; 结果:
{
"path" : " \ dir \ subdir "
}在1.0.6版中,引入了McJsonEscapeString()中使用的TJEscapeType枚举,并具有这些逃生级别:
jetNormal :Escapes #8 #9 #10 #12 #13 " 。jetStrict :正常 + / 。jetUnicode :严格 + uXXXX 。jetNone :向后兼容。这些级别的灵感来自library 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 "
}在内部,它将使用c_empty_key常数字符串作为fkey字段的内容。
由于版本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 。
世界不是完美的,也不是我。这是一些已知问题:
fChild在层次结构中实例化了TMcJsonItem对象,因此创建在项目之间自动传播的字段存在问题。正在研究的解决方案试图创建一个新的父类TMcJson该类别将像根一样,并以TMcJsonItem对象为子。最初的myJSON , LkJson , JsonTools和uJSON单位进行了性能测试。这是测试的摘要。
{... {"keyi":"valuei"}... }以及使用的编译器和机器:
下表总结了结果1 :
| 图书馆 | 产生 | 节省 | 解析 | 加载 | 使用权 | 全部的 |
|---|---|---|---|---|---|---|
McJSON 2 | .11 s | .07 s | .12 s | .09 s | .83 s | 1.25 s |
LkJson 2 | .30 s | .11 s | .47 s | .36 s | .01 s | 1.24 s |
JsonTools | 48.00 s | .70 s | 39.00 s | 40.00 s | .48 s | 1.2分钟 |
myJSON | 50.00 s | .07 s | 5.1分钟 | 7.7分钟 | 1.60 s | 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使代码动词。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 ,但课程的colution也会迫使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