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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14864170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:44:47  来源:igfitidea点击:

How to parse a JSON array in RAd Studio?

jsondelphic++builder

提问by Dabiel Kabuto

I am trying to parse the following Json document:

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

[
  {"EventType":49,"Code":"234","EventDate":"20050202", "Result":1},
  {"EventType":48,"Code":"0120","EventDate":"20130201", "Group":"g1"}
]

I use the following code:

我使用以下代码:

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);

At this point, pair.JsonValueis NULL. What do I need to do to read the values?

此时,pair.JsonValue为NULL。我需要做什么才能读取值?

回答by RRUZ

You are not casting the JSON String properly, you must cast as an TJSONArray and then iterate over the elements.

您没有正确转换 JSON 字符串,您必须转换为 TJSONArray,然后遍历元素。

try these samples

试试这些样品

Delphi

德尔福

{$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++ 生成器

#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;
}

This will return

这将返回

EventType : 49
Code : 234
EventDate : 20050202
Result : 1

EventType : 48
Code : 0120
EventDate : 20130201
Group : g1

回答by Rob Kennedy

You have an invalid type cast, so what you're seeing is undefined behavior. A null result is just oneof the many possible outcomes you could expect from this code. The ParseJSONValuefunction in this case should return a TJsonArray, not a TJsonObject. Although both classes have Getmethods, they're not interchangeable.

你有一个无效的类型转换,所以你看到的是未定义的行为。空结果只是您可以从此代码中期望的众多可能结果之一ParseJSONValue这种情况下的函数应该返回 a TJsonArray,而不是 a TJsonObject。尽管两个类都有Get方法,但它们不能互换。

The array's Getmethod returns a TJsonValue, not a TJsonPair. For this particular data, you can type-cast the value to TJsonObjectbecause your data represents an array of two objects.

数组的Get方法返回 a TJsonValue,而不是 a TJsonPair。对于此特定数据,您可以将值转换为类型,TJsonObject因为您的数据表示包含两个对象的数组。

Use dynamic_castor Delphi's asoperator to cast from one class to another.

使用dynamic_cast或 Delphi 的as运算符从一个类转换到另一个类。

回答by Arioch 'The

dbExpress JSON parser was told to be heavyweight and sometimes problematic.

dbExpress JSON 解析器被告知是重量级的,有时会出现问题。

Perhaps you can choose some of the number of 3rd-party parsers, for example this shows reading array: http://code.google.com/p/superobject/wiki/first_steps

也许您可以选择一些 3rd-party 解析器,例如这显示读取数组:http: //code.google.com/p/superobject/wiki/first_steps

回答by AngeloDM

you can get an array from a JSON string also using the JSonCBuilderBlog Library for C++Builder (free and open source):

您还可以使用 C++Builder 的 JsonCBuilderBlog 库(免费和开源)从 JSON 字符串中获取数组:

UnicodeString JSONSource =
"[{\"EventType\":49,\"Code\":\"234\",\"EventDate\":\"20050202\", \"Result\":1},"
"{\"EventType\":48,\"Code\":\"0120\",\"EventDate\":\"20130201\",\"Group\":\"g1\"}]";

int           Type; 
UnicodeString Code;
UnicodeString Date;
int           Result;

TMetaObject MyArray;

MyArray.Decode(JSONSource);

for(int i=0; i < MyArray.Count(); i++)
{
    Type   = MyArray[i]["EventType"];
    Code   = MyArray[i]["Code"];
    Date   = MyArray[i]["EventDate"];
}

The syntax is very simple, see the following link as reference: JSONCBuilderBloglibrary.

语法很简单,参考以下链接:JSONCBuilderBloglibrary。