Sal*_*dor 16 delphi json delphi-xe
我该如何解析JSON字符串
{"data":{"results":[{"Branch":"ACCT590003"}]}}
Run Code Online (Sandbox Code Playgroud)
使用TJSONObject对象?我想ACCT590003从这个字符串中获取值.
Cha*_*ang 14
uses
SysUtils,
DBXJSON;
type
TProcessJSONString = TProc<TJSONString>;
procedure DoJSONObject(o: TJSONObject; Process: TProcessJSONString); forward;
procedure DoJSONArray(o: TJSONArray; Process: TProcessJSONString);
var i: integer;
v: TJSONValue;
begin
for i := 0 to o.Size - 1 do begin
v := o.Get(i);
if v is TJSONObject then
DoJSONObject(v as TJSONObject, Process);
end;
end;
procedure DoJSONObject(o: TJSONObject; Process: TProcessJSONString);
var i: integer;
p: TJSONPair;
begin
for i := 0 to o.Size - 1 do begin
p := o.Get(i);
Process(p.JsonString);
if p.JsonValue is TJSONObject then
DoJSONObject(p.JsonValue as TJSONObject, Process)
else if p.JsonValue is TJSONArray then
DoJSONArray(p.JsonValue as TJSONArray, Process)
else if p.JsonValue is TJSONString then
Process(p.JsonValue as TJSONString);
end;
end;
var o: TJSONObject;
begin
o := TJSONObject.ParseJSONValue('{"data":{"results":[{"Branch":"ACCT590003"}]}}') as TJSONObject;
try
DoJSONObject(o,
procedure (o: TJSONString)
begin
WriteLn(o.ToString);
end
);
finally
o.Free;
end;
ReadLn;
end.
Run Code Online (Sandbox Code Playgroud)
小智 10
您无需使用外部库即可执行JSONPath搜索。Delphi 10 Seattle的示例:
uses System.JSON;
procedure ParseJSonValue;
var
JSonValue:TJSonValue;
st:string;
Branch: string;
begin
st := '{"data":{"results":[{"Branch":"ACCT590003"}]}}';
JsonValue := TJSonObject.ParseJSONValue(st);
Branch := JsonValue.GetValue<string>('data.results[0].Branch');
JsonValue.Free;
end;
Run Code Online (Sandbox Code Playgroud)
小智 7
试试这个代码,它工作正常
uses System.JSON;
procedure _Parse_JSonValue;
var
JSonObject:TJSonObject;
JSonValue:TJSonValue;
st:string;
Branch: string;
Begin
st := '{"data":{"results":[{"Branch":"ACCT590003"}]}}';
JSonObject := TJSonObject.Create;
JsonValue:=JSonObject.ParseJSONValue(st);
JsonValue:=(JsonValue as TJSONObject).Get('data').JSONValue;
JsonValue:=(JsonValue as TJSONObject).Get('results').JSONValue;
if (JSONValue is TJSONArray) then
Branch := ((JSONValue as TJSONArray).Items[0] as TJSonObject).Get('Branch').JSONValue.Value;
JSonObject.Free;
End;
Run Code Online (Sandbox Code Playgroud)
分支 = 'ACCT590003'
使用TALdocument很容易
AJsonDoc := TalJsonDocument.create;
AjsonDoc.loadFromJsonString('{"data":{"results":[{"Branch":"ACCT590003"}]}}');
writeln(AjsonDoc.childnode['data']['result'][0]['Branch'].text);
Run Code Online (Sandbox Code Playgroud)
使用 SuperObject 库https://github.com/hgourvest/superobject/
var json: iSuperObject;
data: string;
begin
json := SO('{"data":{"results":[{"Branch":"ACCT590003"}]}}'); // shorthand
// or equal: JSON := TSuperObject.ParseString('{"data":{"results":[{"Branch":"ACCT590003"}]}}');
data := json.S['data.results[0].Branch'];
WriteLn('Result is: ', data);
end.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44778 次 |
| 最近记录: |