您没有正确转换 JSON 字符串,您必须转换为 TJSONArray,然后遍历元素。
试试这些样品
德尔福
{$APPTYPE CONSOLE}
uses
DBXJSON,
System.SysUtils;
Const
StrJson =
'['+
'{"EventType":49,"Code":"234","EventDate":"20050202", "Result":1},'+
'{"EventType":48,"Code":"0120","EventDate":"20130201", "Group":"g1"}'+
']';
procedure ParseJson;
var
LJsonArr : TJSONArray;
LJsonValue : TJSONValue;
LItem : TJSONValue;
begin
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(StrJson),0) as TJSONArray;
for LJsonValue in LJsonArr do
begin
for LItem in TJSONArray(LJsonValue) do
Writeln(Format('%s : %s',[TJSONPair(LItem).JsonString.Value, TJSONPair(LItem).JsonValue.Value]));
Writeln;
end;
end;
begin
try
ParseJson;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
C++ 生成器
#include <vcl.h>
#include <windows.h>
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <stdio.h>
#include <DBXJSON.hpp>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
TJSONArray* LJsonArr = (TJSONArray*)TJSONObject::ParseJSONValue(
BytesOf((UnicodeString)"[{\"EventType\":49,\"Code\":\"234\",\"EventDate\":\"20050202\", \"Result\":1}, {\"EventType\":48,\"Code\":\"0120\",\"EventDate\":\"20130201\", \"Group\":\"g1\"}]"),0);
int size = LJsonArr->Size();
for (int i = 0; i < size; ++i)
{
TJSONValue* LJsonValue = LJsonArr->Get(i);
TJSONArray* LJsonArr2 = (TJSONArray*)LJsonValue;
int size2 = LJsonArr2->Size();
for (int j = 0; j < size2; ++j)
{
TJSONValue* LItem = LJsonArr2->Get(j);
TJSONPair* LPair = (TJSONPair*)LItem;
printf("%s %s \n", (UTF8String )(LPair->JsonString->Value()).c_str(), (UTF8String )(LPair->JsonValue->Value()).c_str());
}
}
std::cin.get();
return 0;
}
这将返回
EventType : 49
Code : 234
EventDate : 20050202
Result : 1
EventType : 48
Code : 0120
EventDate : 20130201
Group : g1