Skip to content

Instantly share code, notes, and snippets.

@versionsix
Created May 3, 2022 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save versionsix/311e37d0c77d430204886db746db5b63 to your computer and use it in GitHub Desktop.
Save versionsix/311e37d0c77d430204886db746db5b63 to your computer and use it in GitHub Desktop.
Golang parse json with invalid "string-int" types
package main
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
)
type invalidStrNums []int
type User struct {
Id uint `json:"id"`
//RoleIds []uint `json:"role_ids"`
OtherIds invalidStrNums `json:"other_ids"`
}
func main() {
in := `{"id":96,"other_ids": ["33",55,"66"] }`
var u User
if err := json.Unmarshal([]byte(in), &u); err != nil {
panic("failed")
}
fmt.Printf("%#v", u)
fmt.Println("")
b, _ := json.Marshal(u)
fmt.Println("internal presentation:", string(b))
fmt.Println("")
otherUser := &User{
Id: 69,
OtherIds: []int{5,99},
}
b, _ = json.Marshal(otherUser)
fmt.Println("external presentation: ", string(b))
}
func (c *invalidStrNums) MarshalJSON() ([]byte, error) {
var r []string
for _, item := range *c {
r = append(r, fmt.Sprintf("%v", item))
}
return json.Marshal(r)
}
func (c *invalidStrNums) UnmarshalJSON(b []byte) error {
var n invalidStrNums
fmt.Printf("%v\n", string(b))
fmt.Printf("type: %v , %v\n", reflect.TypeOf(*c), *c)
var nums []interface{}
err := json.Unmarshal(b, &nums)
if err != nil {
return err
}
//fmt.Printf("%v\n", nums)
for _, item := range nums {
switch value := item.(type) {
case int:
n = append(n, item.(int))
case float64:
n = append(n, int(value))
case string:
num, err := strconv.Atoi(value)
if err != nil {
return err
}
n = append(n, num)
}
}
*c = n
return nil
}
/*
["33",55,"66"]
type: main.invalidStrNums , []
main.User{Id:0x60, OtherIds:main.invalidStrNums{33, 55, 66}}
internal presentation: {"id":96,"other_ids":[33,55,66]}
external presentation: {"id":69,"other_ids":["5","99"]}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment