首页 > 解决方案 > 基于条件的不同结果的 JSON 响应 - 需要指南

问题描述

在 JSON 中包含或排除其值取决于另一个字段的字段的最佳方法是什么。在下面的示例中,phone_number 和 email 字段将具有基于 auth_type 字段的值或 null。

在方法 A 中,如果 auth_type 是 phone 则 email 字段不会在 api 响应中发送,但在方法 B 中,如果 auth_type 是 phone 那么 email 字段将发送空值。哪种方法好?

方法一:

{
    id: 123,
    ...
    auth_type: 'Phone',
    phone_number: 123456
}

{
    id: 123,
    ...
    auth_type: 'email',
    email: 'abc@abc.com'
}

方法 B:

{
    id: 123,
    ...
    auth_type: 'Phone',
    phone_number: 123456,
    email: null
}
{
    id: 123,
    ...
    auth_type: 'email',
    phone_number: null,
    email: 'abc@abc.com'
}

标签: jsonrest

解决方案


推荐阅读