如何使用ts.data.json解码嵌套对象

时间:2019-08-15 07:33:18

标签: typescript jsondecoder

我正在尝试使用https://github.com/joanllenas/ts.data.json上的示例来解码和验证Typescript中的json有效负载。可以,但是我想将它用于嵌套数据,例如,用户有一个地址。

我尝试使用JsonDecoder.object作为Address的类型,但这不起作用。我的IDE(IntelliJ)说我需要一个DecoderObject而不是Decoder。谁能推荐我该怎么做?

type Address = {
    street: string;
    town: string; 
    postcode: string;
};


type User = {
    firstname: string;
    lastname: string;
    address: Address;
};

const addressDecoder = JsonDecoder.object<User>(
    {
        street: JsonDecoder.string,
        town: JsonDecoder.string,
        postcode: JsonDecoder.string
    },
    'User'
);


const userDecoder = JsonDecoder.object<User>(
    {
        firstname: JsonDecoder.string,
        lastname: JsonDecoder.string,
        address: JsonDecoder.object(addressDecoder, "AddressDecoder")
    },
    'User'
);

1 个答案:

答案 0 :(得分:0)

首先,在您的示例中,两个解码器具有相同的名称。无论如何,这很简单。

回答您的问题:修复上述问题后,应使用解码器对象替换address解码器,如下所示:

const addressDecoder = JsonDecoder.object<Address>(
    {
        street: JsonDecoder.string,
        town: JsonDecoder.string,
        postcode: JsonDecoder.string
    },
    'Address'
);

const userDecoder = JsonDecoder.object<User>(
    {
        firstname: JsonDecoder.string,
        lastname: JsonDecoder.string,
        address: addressDecoder
    },
    'User'
);

我认为它应该可以正常工作。