如何解析RAD Studio中的JSON数组? [英] How to parse a JSON array in RAd Studio?
本文介绍了如何解析RAD Studio中的JSON数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析以下Json文档:
I am trying to parse the following Json document:
[
{"EventType":49,"Code":"234","EventDate":"20050202", "Result":1},
{"EventType":48,"Code":"0120","EventDate":"20130201", "Group":"g1"}
]
我使用以下代码:
TJSONObject* jsonread0 = (TJSONObject*) TJSONObject::ParseJSONValue(TEncoding::ASCII->GetBytes(Memo1->Lines->Text), 0);
for(int i=0;i<jsonread0->Size();i++)
{
TJSONPair* pair = jsonread0->Get(i);
此时, pair.JsonValue
空值。我需要做些什么来读取这些值?
At this point, pair.JsonValue
is NULL. What do I need to do to read the values?
推荐答案
你不是正确地投射JSON字符串,你必须转换为TJSONArray然后迭代元素。
You are not casting the JSON String properly, you must cast as an TJSONArray and then iterate over the elements.
尝试这些样本
{$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 ++ Builder
C++ Builder
#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
这篇关于如何解析RAD Studio中的JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文