Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Definition order matters with @JsonProperty #19

Open
sp00x opened this issue Apr 2, 2017 · 2 comments
Open

Definition order matters with @JsonProperty #19

sp00x opened this issue Apr 2, 2017 · 2 comments

Comments

@sp00x
Copy link

sp00x commented Apr 2, 2017

I noticed this the scratch-head-a-lot way:

import { serialize, deserialize, JsonProperty } from 'json-typescript-mapper';

class City
{
    @JsonProperty({ clazz: Farm })
    farms: Farm[] = void 0;
}

class Farm 
{
    name: string = void 0;
    
    @JsonProperty({ clazz: Animal })
    animals: Animal[] = void 0;
}

class Animal
{
    type: string = void 0;
    name: string = void 0;
}


let json = {
    farms: [
        {
            name: 'farm 1',
            animals: [
                { type: 'cow', name: 'Cow 1' },
                { type: 'cow', name: 'Cow 2' },
            ]
        }
    ]
}

console.dir(deserialize(City, json), { depth: null });

result:

City {
  farms:
   [ { name: 'farm 1',
       animals:
        [ { type: 'cow', name: 'Cow 1' },
          { type: 'cow', name: 'Cow 2' } ] } ] }

Switch the order so the classes are defined at the time they're referred from @JsonProperty:

import { serialize, deserialize, JsonProperty } from 'json-typescript-mapper';

class Animal
{
    type: string = void 0;
    name: string = void 0;
}

class Farm 
{
    name: string = void 0;
    
    @JsonProperty({ clazz: Animal })
    animals: Animal[] = void 0;
}

class City
{
    @JsonProperty({ clazz: Farm })
    farms: Farm[] = void 0;
}

let json = {
    farms: [
        {
            name: 'farm 1',
            animals: [
                { type: 'cow', name: 'Cow 1' },
                { type: 'cow', name: 'Cow 2' },
            ]
        }
    ]
}

console.dir(deserialize(City, json), { depth: null });

result:

City {
  farms:
   [ Farm {
       name: 'farm 1',
       animals:
        [ Animal { type: 'cow', name: 'Cow 1' },
          Animal { type: 'cow', name: 'Cow 2' } ] } ] }

Might be worth mentioning or looking into.. I spent an hour here before I noticed..

@bassrock
Copy link

bassrock commented Jun 8, 2017

@sp00x But what if the classes are in separate files?

@sp00x
Copy link
Author

sp00x commented Jun 12, 2017

@bassrock I'm guessing it would partially solve itself automatically then as you'd be import'ing them at the top of the file, i.e. before the references.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants