JohnWeisz / TypedJSON

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

Unable to parse complex nested type #173

Closed NeoWu1216 closed 3 years ago

NeoWu1216 commented 3 years ago

Below is my code for creating structures of json tree:

@jsonObject
class Principal {
  @jsonMember
  public type : string;

  @jsonMember
  public value : string;
}

@jsonObject
class PrincipalList {
  @jsonArrayMember(Principal)
  public principals : Principal[];
}

This example works fine:

const res = TypedJSON.parse({type:"AWSAccount", value:"account_id"}, Principal);
console.log(res) // Principal { type: 'AWSAccount', value: 'account_id' }

But this failed to created a useful class:

const res = TypedJSON.parse([{type:"AWSAccount", value:"account_id"}], PrincipalList);
console.log(res) // PrincipalList {}
console.log(res?.principals[0]) // Cannot read property '0' of undefined

Tried Array class as well but no luck. Please let me know which step went wrong. Thanks.

NeoWu1216 commented 3 years ago

So I guess TypedJSON.parseAsArray is the way to go if we want to parse [{type:"AWSAccount", value:"account_id"}]. Maybe that's something to include in the README.md.

Neos3452 commented 3 years ago

Hi @NeoWu1216, I am głąb you were able to find a solution. What do you think about making a PR with a change to the documentation that you find suitable?

NeoWu1216 commented 3 years ago

Sure, created a PR with simple change in readme. Closing this issue for now.