Icon View Thread

The following is the text of the current message along with any replies.
Messages 1 to 5 of 5 total
Thread Fill TStringList from JSON
Thu, Sep 17 2015 8:09 AMPermanent Link

thomh

Trying fill a TStringList from a JSON array:

{
 "Strings": [
   {
     "0": "User One"
   },
   {
     "1": "User Two"
   },
   {
     "2": "User Three"
   },
   {
     "3": "User Four"
   }
 ]
}

var
 myList: TStringList:
begin
 Reader.Initialize(jsonString);
 myList.Load(Reader);
end;

And the result is 4 empty lines in myList.

What is the correct way to do this?

// Thom
Thu, Sep 17 2015 9:19 AMPermanent Link

Tim Young [Elevate Software]

Elevate Software, Inc.

Avatar

Email timyoung@elevatesoft.com

Thom,

<< Trying fill a TStringList from a JSON array:

And the result is 4 empty lines in myList.

What is the correct way to do this? >>

Do you have control over the incoming JSON data ?  What you've posted isn't what the TStrings class normally expects.  It normally expects this:

{ "Count": 4, "Strings": ["User One", "User Two", "User Three", User Four"] }

Tim Young
Elevate Software
www.elevatesoft.com
Thu, Sep 17 2015 10:06 AMPermanent Link

thomh

Tim Young [Elevate Software] wrote:

<<Do you have control over the incoming JSON data ?  What you've posted isn't what the TStrings class normally <<expects.  It normally expects this:
<<{ "Count": 4, "Strings": ["User One", "User Two", "User Three", User Four"] }

Thanks, Tim. That worked.

I would like to have this as part of multipart JSON string which includes several TStringLists. How would I parse something like this?

{
 "TPLUserRoles": {
   "Count": 4,
   "Strings": [
     "BasicUser",
     "DocumentHandler",
     "DocumentManager",
     "Accountant"
   ]
 }
}

I tried overriding TStrings.LoadProperty with:

function TPLUserRoleList.LoadProperty(AReader: TReader): Boolean;
var
 TempPropertyName: String;
begin
 Result := False;
 TempPropertyName := AReader.GetPropertyName;
 if (TempPropertyName <> '') then
 begin
   if SameText(TempPropertyName, 'TPLUserRoles') then
   begin
     AReader.SkipPropertyName;
     AReader.SkipPropertySeparator;
     LoadArray(AReader);
   end
   else
     Result := inherited LoadProperty(AReader);
 end;
end;

but I get the following error:

Persistent load error: Expected "[", instead found { at 21)
Line: 1716

Thanks.

// Thom
Thu, Sep 17 2015 1:39 PMPermanent Link

thomh

Never mind, Tim.
I think I figured it out.
(At least it works)

// Thom
Thu, Sep 17 2015 2:44 PMPermanent Link

Tim Young [Elevate Software]

Elevate Software, Inc.

Avatar

Email timyoung@elevatesoft.com

Thom,

<< Never mind, Tim. I think I figured it out. (At least it works) >>

Just in case there's any question, and for the readers: just publishing a TStrings property will allow it to load as part of any container TPersistent-descendant class.  You don't need to do anything special with LoadProperty, etc.

Tim Young
Elevate Software
www.elevatesoft.com
Image