반응형
문자열을 int64 유형의 Go 값으로 이동 해제할 수 없습니다.
나는 구조가 있다.
type tySurvey struct {
Id int64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
그렇습니다.json.MarshalHTML 페이지에 JSON 바이트를 씁니다.jQuery 수정namejQueries를 사용하여 객체를 인코딩하고 객체의 필드JSON.stringify및 jQuery는 Go 핸들러에 문자열을 게시합니다.
id문자열로 인코딩된 필드입니다.
발송:{"id":1}수신:{"id":"1"}
문제는 말이다json.Unmarshal그 JSON의 마크를 해제하지 못한 이유는id는 정수가 아닙니다.
json: cannot unmarshal string into Go value of type int64
이러한 데이터를 처리하는 가장 좋은 방법은 무엇입니까?모든 필드를 수동으로 변환하고 싶지 않습니다.콤팩트하고 버그가 없는 코드를 쓰고 싶습니다.
인용문은 나쁘지 않다.JavaScript는 int64에서 잘 작동하지 않습니다.
int64 값의 문자열 값으로 json의 마샬을 쉽게 해제할 수 있는 방법을 배우고 싶습니다.
이것은, 다음의 추가에 의해서 처리됩니다.,string태그에 다음과 같이 입력합니다.
type tySurvey struct {
Id int64 `json:"id,string,omitempty"`
Name string `json:"name,omitempty"`
}
이것은 보안관 서류 중간쯤에서 찾을 수 있다.
빈 문자열은 다음을 지정하여 디코딩할 수 없습니다.omitempty부호화시에만 사용되기 때문입니다.
사용하다json.Number
type tySurvey struct {
Id json.Number `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
int 또는 int64의 유형 에일리어스를 생성하여 커스텀 json unmarshaler 샘플코드를 작성할 수도 있습니다.
// StringInt create a type alias for type int
type StringInt int
// UnmarshalJSON create a custom unmarshal for the StringInt
/// this helps us check the type of our value before unmarshalling it
func (st *StringInt) UnmarshalJSON(b []byte) error {
//convert the bytes into an interface
//this will help us check the type of our value
//if it is a string that can be converted into a int we convert it
///otherwise we return an error
var item interface{}
if err := json.Unmarshal(b, &item); err != nil {
return err
}
switch v := item.(type) {
case int:
*st = StringInt(v)
case float64:
*st = StringInt(int(v))
case string:
///here convert the string into
///an integer
i, err := strconv.Atoi(v)
if err != nil {
///the string might not be of integer type
///so return an error
return err
}
*st = StringInt(i)
}
return nil
}
func main() {
type Item struct {
Name string `json:"name"`
ItemId StringInt `json:"item_id"`
}
jsonData := []byte(`{"name":"item 1","item_id":"30"}`)
var item Item
err := json.Unmarshal(jsonData, &item)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", item)
}
언급URL : https://stackoverflow.com/questions/21151765/cannot-unmarshal-string-into-go-value-of-type-int64
반응형
'programing' 카테고리의 다른 글
| Angular 2의 특정 루트에 대해 RouteReuseStrategy shouldDetach를 구현하는 방법 (0) | 2023.03.05 |
|---|---|
| 농담 모의 반응 컨텍스트 (0) | 2023.03.05 |
| redex 툴킷에서 리듀서와 엑스트라 리듀서의 차이점은 무엇입니까? (0) | 2023.03.05 |
| Plask에 JSON을 보내는 중, request.args vs request.형태 (0) | 2023.03.05 |
| MAX(날짜)로 그룹화 (0) | 2023.03.05 |