appvision-gmbh / json2typescript

Map JSON to a TypeScript class with secure type checking!
https://www.npmjs.com/package/json2typescript
MIT License
278 stars 55 forks source link

what this!, return a empty object? #135

Closed imohuan closed 4 years ago

imohuan commented 4 years ago
import {
  JsonConvert,
  JsonObject,
  JsonProperty,
  OperationMode,
  ValueCheckingMode,
} from "json2typescript";

@JsonObject("User")
class User {
  @JsonProperty("username", String)
  username: string;
  @JsonProperty("password", String)
  password: string;
}

const json: object = {
  username: "admin",
  password: "admin",
  other: "other",
};

const jsonConvert = new JsonConvert();
jsonConvert.operationMode = OperationMode.LOGGING;
jsonConvert.ignorePrimitiveChecks = false;
jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL;

const result = jsonConvert.deserializeObject(json, User);
console.log(result, result.username);

return



Receiving JSON object:
{ username: 'admin', password: 'admin', other: 'other' }
Returning CLASS instance:
User {}
----------
User {} undefined

I wrote it against the official code? What did I do wrong?

Why ?

imohuan commented 4 years ago

ts-node 执行代码
版本"json2typescript": "^1.4.1",

andreas-aeschlimann commented 4 years ago

Hello @imohuan and thank you for your question!

I think everything is correct except a little detail:

Important note: You must assign any (valid) value or undefined to your property at initialization, otherwise our mapper does not work and will simply ignore the property.

(from the docs)

Try this and it should work:

@JsonObject("User")
class User {
  @JsonProperty("username", String)
  username: string = "";
  @JsonProperty("password", String)
  password: string = "";
}
imohuan commented 4 years ago

thanks!

Maybe I didn't see it