West Wind Internet and Client Tools
How to use wwJsonSerializer when square brackets are around the JSON string
Gravatar is a globally recognized avatar based on your email address. How to use wwJsonSerializer when square brackets are around the JSON string
  Manni Borg
  All
  Jan 18, 2022 @ 03:38pm

Hello,

I got a JSON response from a REST API which structure looks like this:

[ { "firstName": "Elvis", "lastName": "Presley" } ]

When trying to use wwJsonSerializer to parse it, it's not working. Example:

DO wwclient
DO wwJsonSerializer

TEXT TO lcjson noshow
[
{
"firstName": "Elvis",
"lastName": "Presley"
}
]
ENDTEXT

loSer = CREATEOBJECT("wwJsonSerializer")
loCust = loSer.DeserializeJson(lcJson)

? loCust.firstName
? loCust.lastName

When removing the square bracket at the beginning and at the end of the JSON string, everything works fine.

Is there somethin I'm missing regarding the use of wwJsonSerializer for arrays?

Thanks, Manni

Gravatar is a globally recognized avatar based on your email address. re: How to use wwJsonSerializer when square brackets are around the JSON string
  Rick Strahl
  Manni Borg
  Jan 18, 2022 @ 04:21pm

Square brackets means it's an array. This is an array of one object.

What you get back should a FoxPro collection. To make it clear I'll add a second object here:

DO wwJsonSerializer

TEXT TO lcjson noshow
[
   {
      "firstName": "Elvis",
      "lastName": "Presley"
   },
   {
      "firstName": "Henry",
      "lastName": "Rollins"
   }
]
ENDTEXT

loSer = CREATEOBJECT("wwJsonSerializer")
loCol = loSer.DeserializeJson(lcJson)

FOR EACH loCust IN loCol FoxObject

	? loCust.firstName
	? loCust.lastName

ENDFOR
Gravatar is a globally recognized avatar based on your email address. re: How to use wwJsonSerializer when square brackets are around the JSON string
  Manni Borg
  Rick Strahl
  Jan 18, 2022 @ 06:14pm

Rick, thank you for your reply!

I now found more examples how to deserialize arrays in your awesome and lengthy article Building and Consuming REST API Services with FoxPro

These are some powerful tools you created! Can't wait to dig deeper 😃

© 1996-2024