【问题标题】:parse JSON array with no object name typescript解析没有对象名称打字稿的 JSON 数组
【发布时间】:2023-02-03 23:25:51
【问题描述】:

我有一个没有对象名称的 json 对象数组

[
  {
    "FIRST_NAME": "fname",
    "LAST_NAME": "KSHHS",
    "SERIAL_NO": 905
  },
  {
    "FIRST_NAME": "jhdf",
    "LAST_NAME": "dfdf",
    "SERIAL_NO": 965
  }
]

我试图在我的类具有不同字段名称的打字稿中反序列化它,就像我们在 java 中使用 Jackson Object Mapper 所做的一样。 我的课看起来像:

   import { JsonObject, JsonProperty } from "json2typescript";
    export class Student {
        @JsonProperty('FIRST_NAME', String)
        private firstName?: string;
        @JsonProperty('FIRST_NAME', String)
        private firstName?: string;
        @JsonProperty('SERIAL_NO', number)
        private id?: string;
}
        let response: Student[];
        response = jsonConvert.deserializeArray(json , Student);//json is the Object array

我尝试使用 json2typescript 无法反序列化,因为我的 json 没有对象键,但链接中显示的示例有它。

【问题讨论】:

    标签: node.js json typescript


    【解决方案1】:

    尝试在 Student 类上使用 @JsonObject 注释:

    @JsonObject
    export class Student {
        @JsonProperty('FIRST_NAME', String)
        firstName?: string;
        @JsonProperty('LAST_NAME', String)
        lastName?: string;
        @JsonProperty('SERIAL_NO', Number)
        id?: number;
    }
    

    注意:我省略了 private 关键字,因为默认情况下 TypeScript 中的类字段是公共的,添加 private 会使它们无法从类外部访问。

    【讨论】:

    • 我尝试添加 @JsonObject("Record") 因为它看起来需要类标识符并删除了 private 但它仍然没有
    猜你喜欢
    • 2023-03-25
    • 2020-08-09
    • 2019-10-26
    • 2020-01-08
    • 2019-01-13
    • 1970-01-01
    • 2018-08-29
    • 2013-08-13
    • 1970-01-01
    相关资源
    最近更新 更多