我有一个像这样的 JSON:
\n{\n"Content": [{\n "Identifier": "AABBCC",\n "Description": "test terfdfg",\n "GenericProductIdentifier": "AABBCC",\n "ProductFamilyDescription": "sampling",\n "LifeCycleStatus": "ACTIVE",\n "Price": {\n "Value": 1.00,\n "Quantity": 1000\n },\n "LeadTimeWeeks": "16",\n "FullBoxQty": 200,\n}],\n"TotalElements": 1,\n"TotalPages": 1,\n"NumberOfElements": 1,\n"First": true,\n"Size": 1,\n"Number": 0\n}\nRun Code Online (Sandbox Code Playgroud)\n在 Delphi 10.4 中,我尝试解析它,但无法访问 \'Price\' 中包含的值 \xe2\x80\x8b\xe2\x80\x8b。
\n我写了这样的代码:
\nvar\n vContent: TJSONArray;\n vJson: TJSONObject;\n vContentRow: TJSONObject;\n i,j : Integer;\nbegin\n Memo2.Lines.Clear;\n\n if Memo1.Text = \'\' then\n exit;\n\n vJson := TJSONObject(TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Memo1.Text),0));\n try\n vContent := TJSONArray(vJson.Get(\'Content\').JsonValue);\n\n for i := 0 to Pred(vContent.Count) do\n begin\n vContentRow := TJSONObject(vContent.Items[i]);\n for j := 0 to Pred(vContentRow.Count) do\n begin\n Memo2.Lines.Add(\' \'+ vContentRow.Get(j).JsonString.Value+\' : \'+ vContentRow.Get(j).JsonValue.Value);\n end;\n end;\n\n Memo2.Lines.Add(vContent.Value);\n finally\n\n end;\nend;\nRun Code Online (Sandbox Code Playgroud)\n读取“Price”中包含的值 \xe2\x80\x8b\xe2\x80\x8b 的正确方法是什么?
\n以下是解析 JSON 的示例代码:
uses
System.IOUtils, System.JSON, System.Generics.Collections;
procedure TForm1.Button1Click(Sender: TObject);
procedure GetPrices(const S: string);
var
V: TJsonValue;
O, E, P: TJsonObject;
A: TJsonArray;
begin
V := TJSONObject.ParseJSONValue(S);
if not Assigned(V) then
raise Exception.Create('Invalid JSON');
try
O := V as TJSONObject;
A := O.GetValue<TJsonArray>('Content');
for var I := 0 to A.Count - 1 do
begin
E := A.Items[I] as TJsonObject; // Element
P := E.GetValue<TJsonObject>('Price');
ShowMessage('Value: ' + P.GetValue<string>('Value') + ' ' + 'Quantity: ' + P.GetValue<string>('Quantity'));
end;
finally
V.Free;
end;
end;
var
S: string;
begin
S := TFile.ReadAllText('d:\json.txt'); // Retrieve it using some webservice
GetPrices(S);
end;
Run Code Online (Sandbox Code Playgroud)
请注意,您的 JSON 无效,正确的定义是:
{
"Content": [{
"Identifier": "AABBCC",
"Description": "test terfdfg",
"GenericProductIdentifier": "AABBCC",
"ProductFamilyDescription": "sampling",
"LifeCycleStatus": "ACTIVE",
"Price": {
"Value": 1.00,
"Quantity": 1000
},
"LeadTimeWeeks": "16",
"FullBoxQty": 200
}],
"TotalElements": 1,
"TotalPages": 1,
"NumberOfElements": 1,
"First": true,
"Size": 1,
"Number": 0
}
Run Code Online (Sandbox Code Playgroud)