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

Not getting errors when field present in class is not present on JSON when parsing #201

Open
marlon-sousa opened this issue Nov 4, 2022 · 1 comment

Comments

@marlon-sousa
Copy link

Hello,

I am having an unexpected behavior when parsing, at least as far as I can understand the documentation.

When a required @jsonMember field in class is not present on Json, I expected to have a parse error.
Instead, I apparently got the field either as undefined or not present.

I tested versions from 1.5.0 to 1.8.0 and got the same results:

import "reflect-metadata";
import { jsonMember, jsonObject, TypedJSON } from "typedjson";




@jsonObject
class Response {
    @jsonMember
    // have to mark it with ! because we have no constructor
    id!: number;
    @jsonMember
    // have to mark it with ! because we have no constructor
    firstName!: string;
    @jsonMember
    // have to mark it with ! because we have no constructor
    lastName!: string;
}

const serializer = new TypedJSON(Response);
serializer.config({
    errorHandler: e => { throw e; },
});
const resp = serializer.parse(`{
        "id": 1,
        "firstName": "a",
        "lavstName": "xx",
        "bla": "aaa"
}`);
console.log(resp);

As you can see, we expect a lastName field in the class but JSON has a lavstName, so the @jsonMember lastName is not provided.

I expected an error, but instead I got a Response class with id and firstName set, lastName not set.
The output of this script for me is this:

Response { id: 1, firstName: 'a', lastName: undefined }

I have tried to remove the ! of fields and to create an assignment constructor, with the same response.

To summarize ... my use case is simple:I want to make sure that a given JSON matches the specs of a given class, by specs I mean that all fields listed in the class are present and have the same types also on JSON, although JSON can perfectly contain more fields than the class.

Am I doing something wrong or this library doesn't help in these cases?

@marlon-sousa
Copy link
Author

I forgot to mention that if lastName exists on JSON but its type is not the expected type of JSON ember, then I got an error as expected.

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

1 participant