我有一个带有json的PostgreSQL模式(DisplayInfo和FormatInfo)。这个领域的结构是动态的。
我只能读取和呈现为字符串(在呈现结构中的字符串类型):
[
{
"ID":9,
"Name":"120 №1",
"DisplayInfo":"{\"path\": \"http://path/to/img.png\"}",
"Format":{
"Code":"frame-120",
"Width":120,
"Height":60,
"FormatInfo":"[{\"name\": \"\\u0413\\u043b\\u0430\\u0432\\u043d\\u043e\\u0435 \\u0438\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435\", \"field_type\": \"img\", \"key\": \"path\"}]"
},
"Weight":0.075,
"Application":8,
"Url":"//path/to/game",
"Referrer":""
}
]
但是我希望输出字段DisplayInfo作为JSON对象。怎么做到的?
我的渲染代码:
func renderJSON(w http.ResponseWriter, obj models.Model) {
js, err := json.Marshal(obj)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(js)
}
这个领域的结构是动态的。DisplayInfo可能有“路径”字段,也可能没有。他们可能有更多的字段。
UPD 2.我将DisplayInfo和FormatInfo输出为json对象(而不是字符串),作为整个对象的一部分,如下所示:
[
{
"ID":9,
"Name":"120 №1",
"DisplayInfo":{"path": "http://path/to/img.png"},
"Format":{
"Code":"frame-120",
"Width":120,
"Height":60,
"FormatInfo":[{"name": "\\u0413\\u043b\\u0430\\u0432\\u043d\\u043e\\u0435 \\u0438\\u0437\\u043e\\u0431\\u0440\\u0430\\u0436\\u0435\\u043d\\u0438\\u0435", "field_type": "img", "key": "path"}]
},
"Weight":0.075,
"Application":8,
"Url":"//path/to/game",
"Referrer":""
}
]
UPD 3:结构
实际结构是:
type BannerSerializer struct {
ID int
Name string
DisplayInfo string
Format formatSerializer
Weight float32
Application int
Url string
Referrer string
}
然后我尝试这个结构:
type BannerSerializer struct {
ID int
Name string
DisplayInfo json.RawMessage
Format formatSerializer
Weight float32
Application int
Url string
Referrer string
}
发布于 2015-08-05 06:48:05
假设您有权更改models.Model
,则可以使用只返回原始字符串的自定义解组程序创建自己的类型:
type JSONString string
func (s JSONString) MarshalJSON() ([]byte, error) {
return []byte(s), nil
}
工作示例:
package main
import (
"encoding/json"
"fmt"
)
type JSONString string
func (s JSONString) MarshalJSON() ([]byte, error) {
return []byte(s), nil
}
type Model struct {
ID int
Name string
DisplayInfo JSONString
}
func main() {
data := []byte(`{
"ID":9,
"Name":"120 №1",
"DisplayInfo":"{\"path\": \"http://path/to/img.png\"}"
}`)
var obj Model
err := json.Unmarshal(data, &obj)
if err != nil {
panic(err)
}
// Here comes your code
js, err := json.Marshal(obj)
if err != nil {
panic(err)
}
fmt.Println(string(js))
}
输出:
{"ID":9,“名称”:“120№1",”http://path/to/img.png“:{”路径“:”http://path/to/img.png“}}
游乐场: http://play.golang.org/p/6bcnuGjlU8
发布于 2015-08-05 06:59:28
使用指向json.RawMessage
的指针
type Data struct {
Obj *json.RawMessage
}
操场:http://play.golang.org/p/Qq9IUBDLzJ。
https://stackoverflow.com/questions/31823580
复制相似问题