Beego/Golang – 将查询值转换为结构体

huangapple go评论85阅读模式
英文:

Beego/Golang - Query Values to Struct

问题

我有一个使用Beego框架构建的Golang API,其中有一个查询涉及多个连接,然后返回一个JSON结果。

我希望能够将每一行转换为一个具有更好键名的结构体,例如不是"Stage__Description"而是"Stage"等等...所以我构建了一个ResultMap结构体,其中包含我想要的键名,我应该创建一个Map吗?

查询:

type ResultMap struct {
    Id        int
    DateAdded time.Time
    FirstName string
    LastName  string
    Username  string
    Stage     string
    Station   string
    Status    string
}

//var maps []ResultMap
var maps []orm.Params
num, err := o.QueryTable("test_result_detail").
    Filter("Result__Serial", "121994-0001").
    Values(&maps, "id", "date_added", "stage__description", "station__station", "status__status", "operator__username", "operator__first_name", "operator__last_name")

JSON结果

[
  {
    "DateAdded": "2016-10-20T00:00:00-05:00",
    "Id": 8306105,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "VR1 Test",
    "Station__Station": "TS0653",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-20T00:00:00-05:00",
    "Id": 8306465,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "QA Lab X-Ray Inspection",
    "Station__Station": "LABEQP-0004",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-28T00:00:00-05:00",
    "Id": 8547267,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "Capture Customer SN",
    "Station__Station": "N/A",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-28T00:00:00-05:00",
    "Id": 8547851,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "Final Test",
    "Station__Station": "TS0653",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2017-02-14T00:00:00-06:00",
    "Id": 10993864,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "QA Mechanical Final Inspection",
    "Station__Station": "VISUAL INSPECTION",
    "Status__Status": "PASS"
  }
]
英文:

I have an API built in Golang using the Beego framework and I have a single query that has multiple joins and then returns a JSON result.

I was hoping there is a way for me to cast each row into a struct which has nicer key names, IE rather than "Stage__Description" just "Stage", etc... So I built a ResultMap struct with the key names I want, should I be creating a Map instead?

Query:

type ResultMap struct {
	Id        int
	DateAdded time.Time
	FirstName string
	LastName  string
	Username  string
	Stage     string
	station   string
	status    string
}

//var maps []ResultMap
var maps []orm.Params
num, err := o.QueryTable("test_result_detail").
	Filter("Result__Serial", "121994-0001").
	Values(&maps, "id", "date_added", "stage__description", "station__station", "status__status", "operator__username", "operator__first_name", "operator__last_name" )

JSON RESULT

[
  {
    "DateAdded": "2016-10-20T00:00:00-05:00",
    "Id": 8306105,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "VR1 Test",
    "Station__Station": "TS0653",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-20T00:00:00-05:00",
    "Id": 8306465,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "QA Lab X-Ray Inspection",
    "Station__Station": "LABEQP-0004",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-28T00:00:00-05:00",
    "Id": 8547267,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "Capture Customer SN",
    "Station__Station": "N/A",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2016-10-28T00:00:00-05:00",
    "Id": 8547851,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "Final Test",
    "Station__Station": "TS0653",
    "Status__Status": "PASS"
  },
  {
    "DateAdded": "2017-02-14T00:00:00-06:00",
    "Id": 10993864,
    "Operator__FirstName": "Jose",
    "Operator__LastName": "Mendez",
    "Operator__Username": "3362",
    "Stage__Description": "QA Mechanical Final Inspection",
    "Station__Station": "VISUAL INSPECTION",
    "Status__Status": "PASS"
  }
]

答案1

得分: 1

你想在结构体上使用 JSON 注解,然后使用 json.Unmarshal 将数据放入你的结构体中。

以下是一个示例:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// 你想要存储数据的结构体
	// 注意 JSON 标签,它们显示了哪个 JSON 字段对应哪个结构体字段
	type Data struct {
		FirstName string `json:"Operator__FirstName"`
		LastName  string `json:"Operator__LastName"`
	}
	// 创建一个这些结构体的切片,因为我们的 JSON 是一个结果数组
	var structData []Data

	// 你想要转换为结构体的 JSON 数据
	jsonData := []byte(`[{"Operator__FirstName": "Bob", "Operator__LastName": "Smith"},{"Operator__FirstName": "John", "Operator__LastName": "Adams"}]`)

	_ = json.Unmarshal(jsonData, &structData)

	fmt.Printf("%+v", structData)
}

你可以在 Go Playground 上查看这个示例:https://play.golang.org/p/Z2P7oUVT9i

英文:

You want to use json annotations on your struct, then use json.Unmarshal to put the data into your struct.

Here is an example:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// The struct you want to store the data in
	// Note the json tags that show which json field corresponds to which struct field
	type Data struct {
		FirstName string `json:"Operator__FirstName"`
		LastName  string `json:"Operator__LastName"`
	}
	// Create a slice of these structs since our json is an array of results
	var structData []Data

	// The json you want to dump into the structs
	jsonData := []byte(`[{"Operator__FirstName": "Bob", "Operator__LastName": "Smith"},{"Operator__FirstName": "John", "Operator__LastName": "Adams"}]`)

	_ = json.Unmarshal(jsonData, &structData)

	fmt.Printf("%+v", structData)
}

And here it is in Go Playground: https://play.golang.org/p/Z2P7oUVT9i

答案2

得分: 0

你也可以使用MVC模式。如果你想使用MVC,你需要创建一个models包并将模型注册到数据库中。

package models

import (
	"time"

	"github.com/astaxie/beego/orm"
)

type ResultMap struct {
	Id        int       `orm:"auto"`
	DateAdded time.Time `orm:"type(datetime)"`
	FirstName string    `orm:"size(255)"`
	LastName  string    `orm:"size(255)"`
	Username  string    `orm:"size(255)"`
	Stage     string    `orm:"size(255)"`
	Station   string    `orm:"size(255)"`
	Status    string    `orm:"size(255)"`
}

func init() {
	orm.RegisterModel(
		new(ResultMap),
	)
}

然后你可以在控制器中按照你的需求选择模型作为数据(切片或单个变量)。

func main() {
	var mySlice []models.ResultMap
	_, err := orm.NewOrm().QueryTable("ResultMap").Filter("FirstName", "Bob").All(&mySlice)
	if err != nil {
		fmt.Println("Database Error:", err)
		return
	}

	for _, value := range mySlice {
		fmt.Println("Firstname:", value.FirstName)
	}
}

你可以查看模型定义ORM使用

英文:

You can also use MVC pattern. If you want to use MVC, you need to create models package and register the model to database.

package models

import (
"time"

"github.com/astaxie/beego/orm"
)

type ResultMap struct {
    Id        int    `orm:"auto"`
    DateAdded time.Time    `orm:"type(datetime)"`
    FirstName string     `orm:"size(255)"`
    LastName  string     `orm:"size(255)"`
    Username  string     `orm:"size(255)"`
    Stage     string     `orm:"size(255)"`
    station   string     `orm:"size(255)"`
    status    string     `orm:"size(255)"`
}

func init() {
	orm.RegisterModel(
		new(ResultMap),
    )
}

Then you can select your data as model in your controller as you want(slice or single variable).

func main() {
    var mySlice []models.ResultMap
    _,err := orm.NewOrm().QueryTable("ResultMap").Filter("FirstName","Bob").All(&mySlice)
    if err != nil {
        fmt.Println("Database Error: ",err)
        return
    }

    for _, value := range mySlice {
        fmt.Println("Firstname: ",value.FirstName)
    }
}

You can check model definition and ORM usage

huangapple
  • 本文由 发表于 2017年2月23日 06:46:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/42403742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定