JohnWeisz/TypedJSON

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

Closed this issue · 1 comments

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.

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 21e3228#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).