json-iterator/go

json.Unmarshal loses one array value. "encoding/json" Package shows all.

sikmike opened this issue · 1 comments

Hi,

I have noticed a strange behavior when using jsonitor. When I unmarshal a nested JSON string where the result is an array that contains two elements, one element gets lost during unmarshal.

https://go.dev/play/p/Qwncy1gs6qi

package main

import (
	//"encoding/json"
	"fmt"

	jsoniter "github.com/json-iterator/go"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

type MyResp struct {
	Jsonrpc string   `json:"jsonrpc"`
	Result  []Result `json:"result"`
}
type Medias struct {
	Mediaid     string   `json:"mediaid"`
	Userid      string   `json:"userid"`
	Mediatypeid string   `json:"mediatypeid"`
	Sendto      []string `json:"sendto"`
	Period      string   `json:"period"`
}
type Result struct {
	Userid   string   `json:"userid"`
	Username string   `json:"username"`
	Medias   []Medias `json:"medias"`
}

func main() {
	response := `{
    "jsonrpc": "2.0",
    "result": [
        {
            "userid": "1",
            "username": "username1",
            "medias": [
                {
                    "mediaid": "1",
                    "userid": "1",
                    "mediatypeid": "1",
                    "sendto": [
                        "me@me.com"
                    ],
                    "period": "1"
                },
                {
                    "mediaid": "2",
                    "userid": "1",
                    "mediatypeid": "2",
                    "sendto": "123456789",
                    "period": "1"
                }
            ]
        },
        {
            "userid": "2",
            "username": "username2",
            "medias": [
                {
                    "mediaid": "1",
                    "userid": "2",
                    "mediatypeid": "2",
                    "sendto": [
                        "you@you.com"
                    ],
                    "period": "1"
                },
                {
                    "mediaid": "3",
                    "userid": "2",
                    "mediatypeid": "4",
                    "sendto": "98765434321",
                    "period": "1"
                }
            ]
        }
    ]
}`

	var myResp MyResp
	json.Unmarshal([]byte(response), &myResp)

	for i, user := range myResp.Result {
		fmt.Printf("%d) Userid name: %s \t| Username: %s\n", i, user.Userid, user.Username)
	}
	fmt.Printf("\nResult 0: %v\n", myResp.Result[0])
	fmt.Printf("\nLegth: %v\n", len(myResp.Result))
	//fmt.Printf("\nResult: %v\n", string(response))
}

When I switch to the standard "encoding/json" package both result array values are shown.

I should have checked the err response.

json: cannot unmarshal string into Go struct field Medias.result.medias.sendto of type []string