我正在try 从订阅的条带响应对象的 struct 中获取一些数据.这里是到响应对象stribe subscription object的 struct 的链接

这就是我所拥有的和正在努力做的事情

type SubscriptionDetails struct {
    CustomerId             string  `json:"customer_id"`
    SubscritpionId         string  `json:"subscritpion_id"`
    StartAt                time.Time  `json:"start_at"`
    EndAt                  time.Time  `json:"end_at"`
    Interval               string  `json:"interval"`
    Plan                   string  `json:"plan"`
    PlanId                 string  `json:"plan_id"`
    SeatCount              uint8  `json:"seat_count"`
    PricePerSeat           float64  `json:"price_per_seat"`
}



func CreateStripeSubscription(CustomerId string, planId string) (*SubscriptionDetails, error) {

    stripe.Key = StripeKey

    params := &stripe.SubscriptionParams{
    Customer: stripe.String(CustomerId),
    Items: []*stripe.SubscriptionItemsParams{
        &stripe.SubscriptionItemsParams{
        Price: stripe.String(planId),
        },
    },
    }
    result, err := sub.New(params)

    if err != nil {
        return nil, err
    }

    data := &SubscriptionDetails{}

    data.CustomerId           = result.Customer
    data.SubscritpionId       =  result.ID
    data.StartAt              =  result.CurrentPeriodStart
    data.EndAt                =  result.CurrentPeriodEnd
    data.Interval             =  result.Items.Data.Price.Recurring.Interval
    data.Plan                 =  result.Items.Data.Price.Nickname
    data.SeatCount            =  result.Items.Data.Quantity
    data.PricePerSeat         =  result.Items.Data.Price.UnitAmount


    return data, nil    
}

有一些项目很容易直接获得,比如我用result.ID轻松获得了ID字段,没有投诉,但对于其他项目,这里是我收到的错误消息

cannot use result.CurrentPeriodStart (type int64) as type time.Time in assignment
...
cannot use result.Customer (type *stripe.Customer) as type string in assignment
...
result.Items.Data.price undefined (type []*stripe.SubscriptionItem has no field or method price)

那么我如何获得data.CustomerIddata.PricePerSeat的数据呢?

最新情况:

以下是来自条带的订阅对象的 struct

type FilesStripeCreateSubscription struct {
    ID                    string      `json:"id"`
    CancelAt             interface{}   `json:"cancel_at"`
    CancelAtPeriodEnd    bool          `json:"cancel_at_period_end"`
    CanceledAt           interface{}   `json:"canceled_at"`
    CurrentPeriodEnd     int64         `json:"current_period_end"`
    CurrentPeriodStart   int64         `json:"current_period_start"`
    Customer             string        `json:"customer"`
    Items                struct {
            Data []struct {
                    ID                string      `json:"id"`
                    BillingThresholds interface{} `json:"billing_thresholds"`
                    Created           int64       `json:"created"`
                    Metadata          struct {
                    } `json:"metadata"`
                    Object string `json:"object"`
                    Price  struct {
                            ID               string      `json:"id"`
                            Active           bool        `json:"active"`
                            Currency         string      `json:"currency"`
                            CustomUnitAmount interface{} `json:"custom_unit_amount"`
                            Metadata         struct {
                            } `json:"metadata"`
                            Nickname  string `json:"nickname"`
                            Object    string `json:"object"`
                            Product   string `json:"product"`
                            Recurring struct {
                                    AggregateUsage interface{} `json:"aggregate_usage"`
                                    Interval       string      `json:"interval"`
                                    IntervalCount  int64       `json:"interval_count"`
                                    UsageType      string      `json:"usage_type"`
                            } `json:"recurring"`
                            TaxBehavior       string      `json:"tax_behavior"`
                            TiersMode         interface{} `json:"tiers_mode"`
                            TransformQuantity interface{} `json:"transform_quantity"`
                            Type              string      `json:"type"`
                            UnitAmount        int64       `json:"unit_amount"`
                            UnitAmountDecimal int64       `json:"unit_amount_decimal,string"`
                    } `json:"price"`
                    Quantity     int64         `json:"quantity"`
                    Subscription string        `json:"subscription"`
                    TaxRates     []interface{} `json:"tax_rates"`
            } `json:"data"`
    } `json:"items"`
}

推荐答案

让我们首先回顾一下在引擎盖下工作的代码,返回的内容,然后我们逐一查看问题.

当我们使用params调用sub.New()方法时,它返回Subscription类型,可以看到here

Note:我将只显示类型的有限定义,因为添加完整的 struct 会使答案变得更大,而不是特定于问题上下文

让我们看起来只有Subscription种类型

type Subscription struct {
  ...
  // Start of the current period that the subscription has been invoiced for.
  CurrentPeriodStart int64 `json:"current_period_start"`
  // ID of the customer who owns the subscription.
  Customer *Customer `json:"customer"`
  ...
  // List of subscription items, each with an attached price.
  Items *SubscriptionItemList `json:"items"`
  ...
}

让我们来看一下第一个错误

cannot use result.CurrentPeriodStart (type int64) as type time.Time in assignment

根据Subscription类型,我们可以看到CurrentPeriodStartint64类型,而您试图将其设置为SubscriptionDetails类型的StartAt字段,这是time.Time类型,因为类型不同,所以不能赋值来解决这个问题,我们需要显式地将它转换为time.Time,可以这样做:

data.StartAt = time.Unix(result.CurrentPeriodStart, 0)

然后您可以将time.Unix方法的返回值赋给StartAt字段

现在让我们转到第二个错误

cannot use result.Customer (type *stripe.Customer) as type string in assignment

正如我们从Subscription定义中可以看到的,Customer字段是*Customer类型的,它不是字符串类型,因为您试图将*Customer类型赋给CustomerId字符串类型的字段,这是不可能导致上述错误的,因为我们引用的是不正确的数据,其中正确的数据在*Customer类型的ID字段内可用,可以按如下方式检索

data.CustomerId = result.Customer.ID

让我们回顾一下最后一个错误

result.Items.Data.price undefined (type []*stripe.SubscriptionItem has no field or method price)

同样,如果我们查看Subscription个定义,我们可以看到Items个字段的类型为*SubscriptionItemList,我们查看的是*SubscriptionItemList个定义

type SubscriptionItemList struct {
    APIResource
    ListMeta
    Data []*SubscriptionItem `json:"data"`
}

它包含字段名Data,数据类型为[]*SubscriptionItem.请注意,它是*SubscriptionItem的片[],现在让我们来看看*SubscriptionItem的定义

type SubscriptionItem struct {
  ...
  Price *Price `json:"price"`
  ...
}

它包含Price个字段,注意名称以大写字母开头,最后如果我们看一下Price的定义

type Price struct {
  ...
  // The unit amount in %s to be charged, represented as a whole integer if possible. Only set if `billing_scheme=per_unit`.
  UnitAmount int64 `json:"unit_amount"`

  // The unit amount in %s to be charged, represented as a decimal string with at most 12 decimal places. Only set if `billing_scheme=per_unit`.
  UnitAmountDecimal float64 `json:"unit_amount_decimal,string"`
  ...
}

它包含UnitAmount字段,这是我们需要的,但这里有一个捕获UnitAmount是类型int64,但PricePerSeat是类型float64,所以你可能需要UnitAmountDecimal,根据要求是float64类型,所以根据解释,我们可以解决如下问题

data.PricePerSeat = result.Items.Data[0].Price.UnitAmountDecimal

Json相关问答推荐

JOLT转换过滤出特定值/对象

在Jenkins中使用ReadJSON读取json子元素

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

在Zig中解析JSON失败

VBA json按特定属性名称提取所有数据

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

如何使用 JOLT 使用输入数组中的值和层次 struct 中的其他字段创建数组

VSCode 为 python 文件添加标尺,但不为 C 文件添加标尺.为什么?

Spark-SQL中的from_unixtime函数未能给出正确的输出

将JSON行转换为TSV格式, for each 数组项生成单独的行

使用jq根据对象中键的值查找对象

jq :遍历 json 并在键存在时检索集合

使用本地 JSON api react TS Axios

将请求中的数据推送到数组中

Oracle Apex - 将 JSON 对象分配给变量以返回

坚持弄清楚如何使用 api 响应来调用以从不同的链接检索响应

在 rust 中从 API 反序列化 serde_json

Jolt - 在同一级别添加时组合值的问题

从多维数组数据生成json字符串

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?