Skip to content

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

@marlon-sousa

Description

@marlon-sousa

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions