Go 구조체를 JSON으로 변환
json
패키지를 사용하여 Go 구조체를 JSON으로 변환하려고 하지만 얻는 것은 {}
입니다. 나는 그것이 완전히 명백한 것이 확실하지만 그것을 보지 못한다.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
name string
}
func main() {
user := &User{name:"Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Printf("Error: %s", err)
return;
}
fmt.Println(string(b))
}
그런 다음 실행하려고하면이를 얻습니다.
$ 6g test.go && 6l -o test test.6 && ./test
{}
당신은 할 필요가 수출User.name
있도록 필드에 json
패키지를 볼 수 있습니다. name
필드 이름을로 바꿉니다 Name
.
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
산출:
{"Name":"Frank"}
관련 문제 :
구조체를 JSON으로 변환하고 Golang의 응답으로 보낸 다음 나중에 Ajax를 통해 JavaScript에서 동일하게 catch하는 데 문제가있었습니다.
많은 시간을 낭비 했으므로 여기에 솔루션을 게시하십시오.
이동 중 :
// web server
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)
자바 스크립트에서 :
// web call & receive in "data", thru Ajax/ other
var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);
이것이 누군가를 돕기를 바랍니다.
행운을 빌어 요.
구조 값은 JSON 객체로 인코딩됩니다. 다음과 같은 경우를 제외하고 내 보낸 각 구조체 필드는 객체의 멤버가됩니다.
- 필드의 태그가 "-"이거나
- the field is empty and its tag specifies the "omitempty" option.
The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.
You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:
package main
import (
"fmt"
"encoding/json"
)
type User struct {
name string
}
func (u *User) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name"`
}{
Name: "customized" + u.name,
})
}
func main() {
user := &User{name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}
참고URL : https://stackoverflow.com/questions/8270816/converting-go-struct-to-json
'IT' 카테고리의 다른 글
Selenium WebDriver를 사용하여 요소가 존재하는지 테스트합니까? (0) | 2020.06.12 |
---|---|
Mathematica 도구 가방에 무엇입니까? (1) | 2020.06.12 |
파이썬에서 객체의 유형을 비교하는 방법은 무엇입니까? (0) | 2020.06.12 |
JUnit 5 : 예외를 선언하는 방법은 무엇입니까? (0) | 2020.06.12 |
Div 높이 100 % 및 컨텐츠에 맞게 확장 (0) | 2020.06.12 |