在Golang中将JSONSchema解析为struct类型

时间:2018-06-06 11:32:32

标签: go struct runtime

因此,我的用例包括将不同的JSON模式解析为新的结构类型,这将进一步与ORM一起用于从SQL数据库中获取数据。在编译本质上,我相信不会有一个开箱即用的解决方案,但是有没有可用的黑客可以做到这一点,而无需创建一个单独的go过程。我尝试过反思,但找不到令人满意的方法。

目前,我正在使用生成结构的a-h generate库,但我仍然坚持如何在运行时加载这些新的结构类型。

修改

示例JSON架构:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Address",
  "id": "Address",
  "type": "object",
  "description": "address",
  "properties": {
    "houseName": {
      "type": "string",
      "description": "House Name",
      "maxLength": 30
    },
    "houseNumber": {
      "type": "string",
      "description": "House Number",
      "maxLength": 4
    },
    "flatNumber": {
      "type": "string",
      "description": "Flat",
      "maxLength": 15
    },
    "street": {
      "type": "string",
      "description": "Address 1",
      "maxLength": 40
    },
    "district": {
      "type": "string",
      "description": "Address 2",
      "maxLength": 30
    },
    "town": {
      "type": "string",
      "description": "City",
      "maxLength": 20
    },
    "county": {
      "type": "string",
      "description": "County",
      "maxLength": 20
    },
    "postcode": {
      "type": "string",
      "description": "Postcode",
      "maxLength": 8
    }
  }
}

现在,在上面提到的库中,有一个命令行工具,它为上面的json生成struct类型的文本,如下所示:

// Code generated by schema-generate. DO NOT EDIT.

package main

// Address address
type Address struct {
  County string `json:"county,omitempty"`
  District string `json:"district,omitempty"`
  FlatNumber string `json:"flatNumber,omitempty"`
  HouseName string `json:"houseName,omitempty"`
  HouseNumber string `json:"houseNumber,omitempty"`
  Postcode string `json:"postcode,omitempty"`
  Street string `json:"street,omitempty"`
  Town string `json:"town,omitempty"`
}

现在,问题是如何在程序中重新编译时使用此结构类型。有一个hack,我可以在那里开始一个新的go过程,但这似乎不是一个好方法。另一种方法是编写我自己的解析器来解组JSON模式,例如:

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
for k, v := range m {
    switch vv := v.(type) {
    case string:
        fmt.Println(k, "is string", vv)
    case float64:
        fmt.Println(k, "is float64", vv)
    case int:
        fmt.Println(k, "is int", vv)
    case []interface{}:
        fmt.Println(k, "is an array:")
        for i, u := range vv {
            fmt.Println(i, u)
        }
    default:
        fmt.Println(k, "is of a type I don't know how to handle")
    }
}

有人可以建议一些寻找指针。感谢。

1 个答案:

答案 0 :(得分:1)

所以看起来你正在尝试实施自己的json编组。这没什么大不了的:标准的json包已经支持了。只需让您的类型实现MarshalJSONUnmarshalJSON函数(参见the docs上的第一个示例)。假设某些字段将被共享(例如schema,id,type),您可以创建一个统一的类型:

// poor naming, but we need this level of wrapping here
type Data struct {
    Metadata
}

type Metadata struct {
    Schema string `json:"$schema"`
    Type string `json:"type"`
    Description string `json:"description"`
    Id string `json:"id"`
    Properties json.RawMessage `json:"properties"`
    Address *Address `json:"-"`
    // other types go here, too
}

现在所有属性都将被解组到json.RawMessage字段中(实际上这是一个[]byte字段)。您现在可以在自定义unmarshall函数中执行的操作是这样的:

func (d *Data) UnmarshalJSON(b []byte) error {
    meta := Metadata{}
    // unmarshall common fields
    if err := json.Unmarshal(b, &meta); err != nil {
        return err
    }
    // Assuming the Type field contains the value that allows you to determine what data you're actually unmarshalling
    switch meta.Type {
    case "address":
        meta.Address = &Address{} // initialise field
        if err := json.Unmarshal([]byte(meta.Properties), meta.Address); err != nil {
            return err
        }
    case "name":
        meta.Name = &Name{}
        if err := json.Unmarshal([]byte(meta.Properties), meta.Name); err != nil {
            return err
        }
    default:
        return errors.New("unknown message type")
    }
    // all done
    d.Metadata = meta // assign to embedded
    // optionally: clean up the Properties field, as it contains raw JSON, and is exported
    d.Metadata.Properties = json.RawMessage{}
    return nil
}

你可以为编组工作做同样的事情。首先找出你实际使用的类型,然后将该对象封送到属性字段中,然后然后整个结构

func (d Data) MarshalJSON() ([]byte, error) {
    var (
        prop []byte
        err error
    )
    switch {
    case d.Metadata.Address != nil:
        prop, err = json.Marshal(d.Address)
    case d.Metadata.Name != nil:
        prop, err = json.Marshal(d.Name) // will only work if field isn't masked, better to be explicit
    default:
        err = errors.New("No properties to marshal") // handle in whatever way is best
    }
    if err != nil {
        return nil, err
    }
    d.Metadata.Properties = json.RawMessage(prop)
    return json.Marshal(d.Metadata) // marshal the unified type here
}
相关问题