[Cuis-dev] JSON encoding and decoding

Mariano Montone marianomontone at gmail.com
Mon Jun 17 07:54:14 PDT 2024


El 17/6/24 a las 10:56, Mark Volkmann escribió:
> 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.
Yes. That's the common way of working with JSON.
> 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?

Your implementations are fine IMO. I would consider working directly 
with streams instead of strings in #fromJson:

fromJson: aStream
     | jsonObject |
     jsonObject := Json readFrom: aStream
         id: (jsonObject at: #id)
         name: (jsonObject at: #name)

         breed: (jsonObject at: #breed)


But do what you think is better for your program.


       Mariano
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20240617/5364c72f/attachment.htm>


More information about the Cuis-dev mailing list