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

typed arrays deserialiZation #198

Closed hshahi closed 1 year ago

hshahi commented 1 year ago

Hi

I am struggleing to make things work for scenario below @jsonobject('MyClass') class MyClass { }

@jsonobject('MyClassList') MyClassList extends Array{ }

can you give me an example how to call jsonconvert.deserialise(json, MyClassList); json is from httpclient.get()

Please give an example

Thanks Shahi

andreas-aeschlimann commented 1 year ago

The line MyClassList extends Array does not make sense to me. You can only use classes with the JsonObject decorator.

If you want to deserialize an array of MyClass, please refer to the docs how to do it. You can do it without a MyClassList construct.

hshahi commented 1 year ago

sorry it is @JsonObject('MyClassList') MyClassList extends Array { giveMe3rdItem() {} }

it is to do with the fact I want to use typesafe collection so that it can have its own methods. I can not use it with MyClass[] and giveMe3rdItem() has to reside somewhere else. That is the whole point.

hshahi commented 1 year ago

sorry it is Array< MyClass > { giveMe3rdItem() {} }

it is to do with the fact I want to use typesafe collection so that it can have its own methods. I can not use it with MyClass[] and giveMe3rdItem() has to reside somewhere else. That is the whole point.

andreas-aeschlimann commented 1 year ago

Please set up a Stackblitz where you show example JSON string and what you want to achieve when deserializing. Otherwise it is hard to understand.

hshahi commented 1 year ago

Hi, It is easy, have a entity class say "student" with name and surname property and then have "StudentList" class that inherit from Array< Student > having applied @jsonobject and @jsonproperty applied to them.

then have a json array of the following const jsonString = ' [ { "Name": "Senpai", "Surname": "Stevens" }, { "Name": "Yui Rio", "Surname": "Stevens" } ]';

then call

let jsonConvert: JsonConvert = new JsonConvert();

    try {
        const jsonObject = JSON.parse(jsonString);
        const studentlist = jsonConvert.deserializeObject(jsonObject, StudentList);

    } catch (e) {
        console.log((<Error>e));
    }     
andreas-aeschlimann commented 1 year ago

Just use deserializeArray(jsonObject, Student).

If you want to map your json to a StudentList, it will not work out of the box. I think you will need to do some additional work with the JsonCustomConvert. You will find some help in the docs how to do it.

If you need further support, I suggest you to check the docs or consult a platform like StackOverflow.