无法将嵌套的json字符串解析为Golang中的Struct字段

时间:2019-07-08 10:50:48

标签: go google-cloud-datastore

我正在使用go编写后端以在数据存储区中执行CRUD操作。其中一种“规则”具有以下字段: 名称/ ID(由DS本身生成)数字ID, 名称字符串,活动布尔值,条件条件。

结构规则的结构如下:

type Rule struct {
  Name       string    `json:"name" datastore:"name,noindex"`
  Active     bool      `json:"isActive" datastore:"active,noindex"`
  Condition  condition `json:"condition" datastore:"condition,noindex"`
 }

条件也是一种结构-

type condition struct {
  AdTargetingLogic adTargetingLogic `json:"adTargetingLogic" 
  datastore:"adTargetingLogic,noindex"`
  AdUnit    string `json:"adUnit" datastore:"adUnit,noindex"`
}

AdTargetingLogic是另一个结构-

type AdTargetingLogic struct {
 Type      string       `json:"type" datastore:"type,noindex"`
 Operands  []operands   `json:"operands" datastore:"operands,noindex"`
 Operator  string       `json:"operator" datastore:"operator,noindex"`
}

Operands是另一个结构-

type operands struct {
 Type   string      `json:"type" datastore:"type,noindex"`
 Key    string      `json:"key" datastore:"key,noindex"`
 Value  string      `json:"value" datastore:"value,noindex"`
}

在将规则保存和检索为数据存储区实体时,由于条件字段的嵌套结构,我遇到了问题。如果条件字段的结构没有像这样嵌套-

{"adTargetingLogic":{"operator":"AND","type":"EXPRESSION","operands":[{"key":"artlen","value":"small","type":"MATCH_AD_TARGETING"}]},"adUnit":"fiction"}

一切正常,但对于嵌套结构的条件字段来说

{"adTargetingLogic":{"operator":"AND","type":"EXPRESSION","operands":[{"type":"MATCH_AD_TARGETING","key":"spon","value":"spon1"},{"key":"","value":"","type":"MATCH_AD_TARGETING"},{"operands":[{"type":"MATCH_AD_TARGETING","key":"trend","value":"trend1"},{"type":"MATCH_AD_TARGETING","key":"","value":""}],"operator":"AND","type":"EXPRESSION"}]},"adUnit":"fashion"}

问题不起作用。要解决此问题,在保存实体Rule时,我试图将条件字段编组为-

     data, err := json.Marshal(ruleJS.Condition)
     if err!= nil {
       log.Errorf(ctx,"Marshal ERROR for rules %+v",err)
      }
    log.Errorf(ctx,"Marshal data for rules  %+v",data)
    ruleDS.Condition    = string(data)

与此类似,在检索时,我将其编组为-

    rJs := condition{}
    err := json.Unmarshal([]byte(ruleDS.Condition), &rJs)
     if err != nil {
       log.Errorf(ctx," error while unmarshaling rules  %+v",err)
     }
     ruleJS.Condition  =  rJs

我不知道该如何解决才能使其正常工作。

0 个答案:

没有答案
相关问题