Question

I created a simple test app in Delphi XE6, I want to start using Delphi's JSON to handle requests from a custom coded web server (one I am busy with)

procedure TForm1.Button1Click(Sender: TObject);
var
  Servermethods : TServerMethods1Client;
  JsonArray : TJSONArray;
  JsonValue: TJSONValue;
  JSonObj: TJSONObject;
  JSPair: TJSONPair;
  s: String;
begin
  JSonObj := TJSONObject.Create;
  JSonObj.AddPair(TJSONPair.Create('a','abcde'));
  JsonArray := TJSONArray.Create;
  JsonArray.AddElement(JSonObj);

  JsonValue := JsonArray.Items[0];
  JSonObj := (JsonValue as TJSONObject);

  JSPair := TJSONPair(JSonObj);

  s := JSPair.JsonString.Value;
end;

When you Inspect/Evaluate any JSON object (CTRL+F7) there is simply no info, in the inspector I simply get "()" -[aka empty]-

But for arguments sake if I change the call to JSONObj.Tostring I get the full json string ({"a", "abcde"}) and thats cool thats cool but when it gets to the last line

s := JSPair.JsonString.Value;

Boom! Access Violation.

Any help would be appreciated

* Edit * What I'm actually asking i for someone to test this in XE6 to see if it's a bug? or am I missing something very obvious?

Was it helpful?

Solution

The JSONPair is part of the JSONObject, so you cannot cast the JSONObject to a JSONPair. Use JSONObject.Get to get the pair.

OTHER TIPS

It seems to me that you are also casting a TJSONValue to a TJSONPair.

The last few lines assign a standalone TJSONValue object to JSONObj. Then that is cast to a JSONPair. (in the unsafe way - there is no runtime type compatiblity check then). I think a value here is just a member of a pair and is not compatible with that otherwise.

You could try using "as" operator in that case too, might make discovering the features a lot easier for you.

I.e.

JSPair := JSonObj as TJSONPair;

should complain for the typecasting issue when run.

It would also tell if I am right to say these classes are really sitting on different "benches" of the class inheritance tree, and hence your access violation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top