gpt4 book ai didi

json - 如何在 RAd Studio 中解析 JSON 数组?

转载 作者:行者123 更新时间:2023-12-03 15:37:13 25 4
gpt4 key购买 nike

我正在尝试解析以下 Json 文档:

[
{"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为NULL。我需要做什么才能读取这些值?

最佳答案

您没有正确转换 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

关于json - 如何在 RAd Studio 中解析 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com