[Cuis-dev] JSON encoding and decoding
Mark Volkmann
r.mark.volkmann at gmail.com
Mon Jun 17 06:56:15 PDT 2024
It occured to me that the reason the JSON package does not define a method
that generates JSON from an arbitrary object is that it does not want to
assume that including the value of every instance variable is what you
want. So it requires you to implement the instance method jsonWriteOn:` in
each of your custom classes that need to be converted to a JSON string. I
think you also need to implement a class method in each of those
custom classes that takes a JSON string and returns an object created from
it. Here's an example. I'm curious if anyone thinks this is not the
intended use of the JSON package.
Feature require: 'JSON'
I have a class named VDog that contains the instance variables id, name,
and breed.
Here is my instance method to generate a JSON string:
jsonWriteOn: aWriteStream
{
#id->id.
#name->name.
#breed->breed
} asDictionary jsonWriteOn: aWriteStream
Here is my class method to create a VDog object from a JSON string.
It uses my class method id:name:breed: to create a new instance.
fromJson: aString
| jsonObject |
jsonObject := Json readFrom: aString readStream.
^VDog
id: (jsonObject at: #id)
name: (jsonObject at: #name)
breed: (jsonObject at: #breed)
Would you do this any differently?
On Sun, Jun 16, 2024 at 9:35 PM Ezequiel Birman via Cuis-dev <
cuis-dev at lists.cuis.st> wrote:
> There is *Json class >> renderInstanceVariables:of:on:*. It generates a
> Dictionary. It still relies on Json class >> render, but may be enough for
> what you are trying to do.
>
> Example:
> *Json renderInstanceVariables: Smalltalk class instVarNames of: Smalltalk
> on: Transcript.*
>
> On Mon, 17 Jun 2024 at 01:27, Mariano Montone via Cuis-dev <
> cuis-dev at lists.cuis.st> wrote:
>
>>
>> El 16/6/24 a las 20:25, Mark Volkmann escribió:
>> > The WebClient package can generate JSON from a Dictionary.
>> > Does Cuis provide a method that generates a Dictionary from the
>> > instance properties of an arbitrary Object?
>> > I looked for a method in Object or Dictionary that does that
>> > conversion and couldn't find one.
>>
>> I believe there's no such method. Try to implement it yourself. Look at
>> #allInstVarNames and #instVarNamed: .
>>
>> If you fail, let me know and I will give it a try.
>>
>>
>> --
>> Cuis-dev mailing list
>> Cuis-dev at lists.cuis.st
>> https://lists.cuis.st/mailman/listinfo/cuis-dev
>>
> --
> Cuis-dev mailing list
> Cuis-dev at lists.cuis.st
> https://lists.cuis.st/mailman/listinfo/cuis-dev
>
--
R. Mark Volkmann
Object Computing, Inc.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20240617/75934263/attachment.htm>
More information about the Cuis-dev
mailing list