JohnWeisz / TypedJSON

Typed JSON parsing and serializing for TypeScript that preserves type information.
MIT License
603 stars 64 forks source link

Can you suggest how to setup a member that is an array of string:string dictionaries #115

Closed spayne closed 4 years ago

spayne commented 5 years ago

Can you suggest how to do the following please?

I have a member called localization that wants to be serialized (using TypedJSON) from typescript into json like so: "localization" : [ { "language_tag": "en_us", "/actions/main" : "My Game Actions", "/actions/driving" : "Driving", }, { "language_tag": "fr", "/actions/main" : "Mes actions de jeux", "/actions/driving" : "Conduire", } ]

In typescript I was declaring the localization member using localization : any[] = [] But I don't have to do it this way if you can suggest is a simpler way to setup an array of string keyword:value dictionaries that can serialize as shown above. ie I can change my typescript but can't control the serialized version of it.

Neos3452 commented 5 years ago

Hey Spayne, sorry for a late reply. You could just use Object type like below. I've also added a test so you can see that in action https://github.com/JohnWeisz/TypedJSON/commit/21e3228b142d8d255a9adb62f99a17acd6a5f028#diff-2c1b337a9e33537e7f7d6276a3a0b55f

    @jsonObject
    class Translations {
        @jsonArrayMember(Object)
        localization: any[];
    }

However, you could also do something even more cool. It seems your objects follow a particular structure so you could make use of that to have more advanced type checks and suggestions.

    @jsonObject({
        initializer: (sourceObject, rawSourceObject) => Object.assign(new Localization(), rawSourceObject),
    })
    class Localization {
        @jsonMember
        language_tag: string;

        [trKey: string]: string;
    }

    @jsonObject
    class Translations {
        @jsonArrayMember(Localization)
        localization: Localization[];
    }

The trick here is to use the initializer option that has access to the raw object. You can instantiate your class and assign the dynamic properties there (here I assign everything).