Como converter uma string para um Json Array?
Muitas vezes temos um json recuperado de uma url ou salvo em
um banco de dados como uma string.
Para poder manipular o mesmo, geralmente precisamos de um TJsonArray.
Logo, veja como é simples fazer a conversão.
Vamos ao exemplo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| {$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(aStringJson : string);
var
LJsonArr : TJSONArray;
LJsonValue : TJSONValue;
LItem : TJSONValue;
begin
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(aStringJson),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( StrJson );
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end. |
{$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(aStringJson : string);
var
LJsonArr : TJSONArray;
LJsonValue : TJSONValue;
LItem : TJSONValue;
begin
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(aStringJson),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( StrJson );
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Fonte Base: https://stackoverflow.com/questions/14864170/how-to-parse-a-json-array-in-rad-studio
Dúvidas ou sugestões? Deixe o seu comentário!
-
Giovani Da Cruz
-
30.393 views
- 2 comentários
- 27 de maio de 2017
Está gostando do conteúdo? Considere pagar um cafezinho para nossa equipe!
Posts Relacionados - Continue Aprendendo
Bom artigo… Obrigado!
Para o erro de Undeclared identifier: ‘TJSONArray’ declare System.Json no uses.