2

I have to place a JSON string to a HTTP request's body. One of the string value must be a JSON array. This is how I tried:

uses
  DBXJSON;

const
  cContent = 'hello world';
var
  LJSONObject: TJSONObject;
  x: TBytes;
  i: integer;
  Temp: string;
begin
  LJSONObject:= TJSONObject.Create;
  LJSONObject.AddPair('id1', 'value1');
  LJSONObject.AddPair('id2', 'value2');
  LJSONObject.AddPair('id2', 'value3');

  x:= TEncoding.ANSI.GetBytes(cContent);
  Temp:= '';
  for i := 0 to Length(x) - 1 do
    Temp:= Temp + IntToStr(x[i]) + ',';
  Delete(Temp, Length(Temp), 1);

  LJSONObject.AddPair('id4', '[' + Temp + ']');

  ShowMessage(LJSONObject.ToString);
end;

This one is not working, because the value will be encapsulated in double quotes. What is the proper way to pass an array value to the JSONObject?

2
  • You are passing a string. Pass a TJSONArray. What you are doing is weird though. ANSI? Why an array anyway. The content is a string. Commented Aug 3, 2015 at 5:19
  • The receiver side is waiting for array. I know I should pass an Array, but I dont know how. This is a test code, don't worry about the ANSI :) Commented Aug 3, 2015 at 5:29

1 Answer 1

2

You are passing a string rather than an array. Hence the result you observe. As a rule, if you find yourself assembling the JSON manually, you are doing it wrong.

Pass an array:

var
  arr: TJSONArray;
  b: Byte;
....
arr := TJSONArray.Create;
for b in TEncoding.ANSI.GetBytes(cContent) do
  arr.Add(b);
LJSONObject.AddPair('id4', arr);
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried similar solution, the problem is the "arr.AddElement(b)". Compiler says "Incompatible types: TJSonValue an Byte". The addElement() accept TJSonValue param only. I'm using XE4 if it matters.
Sorry, the method is Add
Works fine! Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.