delphi使用System.JSON解析jsonarray

delphi parse jsonarray with System.JSON

  • 嗨Delphi xe8

    System.JSON

    无法解析jsonarray

    杰森

{"data":{"current_condition":[ {"cloudcover":"0",
"FeelsLikeC":"-9","FeelsLikeF":"15","humidity":"93",
"observation_time":"04:10 AM","precipMM":"0.0","pressure":"1007",
"temp_C":"-6","temp_F":"21","visibility":"10","weatherCode":"113",
"weatherDesc":[],"weatherIconUrl":[],"winddir16Point":"SE",
"winddirDegree":"130","windspeedKmph":"7","windspeedMiles":"4" } ] }
}

1
2
3
4
5
6
7
8
9
10
memores: TStringList;
currcond: TJSONObject;

memores2.Text := http.Get ('url');
JSONObject := TJSONObject.ParseJSONValue(memores2.Text) as TJSONObject;
Memores1.add('current_condition');
JSONObject2 := JSONObject.GetValue('data')   as TJSONObject;
arrayjson := JSONObject2.ParseJSONValue('current_condition')  as TJSONArray;
currcond := arrayjson.Items[0] as TJSONObject;
memores1.Add((currcond.GetValue('cloudcover').Value));


1
arrayjson:=JSONObject2.ParseJSONValue('current_condition')  as TJSONArray;

这会尝试解析文本

1
current_condition

,好像是JSON。它不是。因此,arrayjsonnil,从而导致运行时错误。将该代码行替换为:

1
arrayjson := JSONObject2.GetValue('current_condition') as TJSONArray;

例如,此程序:

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
{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.JSON;

const
  Text =
    '{"data":{"current_condition":[ {"cloudcover":"0","FeelsLikeC":"-9","FeelsLikeF":"15","humidity":"93", ' +
    '"observation_time":"04:10 AM","precipMM":"0.0","pressure":"1007","temp_C":"-6","temp_F":"21","visibility":"10", ' +
    '"weatherCode":"113","weatherDesc":[],"weatherIconUrl":[],"winddir16Point":"SE","winddirDegree":"130","windspeedKmph":"7","windspeedMiles":"4" } ] } }';

procedure Main;
var
  JSONObject, JSONObject2, currcond: TJSONObject;
  arrayjson: TJSONArray;
begin
  JSONObject := TJSONObject.ParseJSONValue(Text) as TJSONObject;
  JSONObject2 := JSONObject.GetValue('data') as TJSONObject;
  arrayjson := JSONObject2.GetValue('current_condition') as TJSONArray;
  currcond := arrayjson.Items[0] as TJSONObject;
  Writeln(currcond.GetValue('observation_time').Value);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

输出

1
04:10 AM

在上面的简单代码中,我没有尝试添加错误检查。您应该这样做。