goccy / go-json

Fast JSON encoder/decoder compatible with encoding/json for Go
MIT License
3.12k stars 148 forks source link

Struct not filled with all possible fields after UnmarshalTypeError #464

Open fabionb opened 1 year ago

fabionb commented 1 year ago

If I have 3 fields in a struct and the second one has a different type between the struct and the incoming json, encoding/json fills the struct with the other 2 fields but the goccy/go-json is filling the struct until the first UnmarshalTypeError.

This could be seen in the following test:

import (
    "encoding/json"
    "testing"

    gojson "github.com/goccy/go-json"
    "github.com/stretchr/testify/assert"
)

type testStruct struct {
    Name        string
    Value       int
    Description string
}

func TestIncompatibility(t *testing.T) {
    jsonValue := []byte("{\"Name\":\"Test Name\",\"Value\":\"incorrect\",\"Description\":\"Test Description\"}")

    jsonData := testStruct{}
    err := json.Unmarshal(jsonValue, &jsonData)
    assert.IsType(t, &json.UnmarshalTypeError{}, err)

    gojsonData := testStruct{}
    err = gojson.Unmarshal(jsonValue, &gojsonData)
    assert.IsType(t, &gojson.UnmarshalTypeError{}, err)

    assert.Equal(t, "Test Name", jsonData.Name)
    assert.Equal(t, "Test Name", gojsonData.Name)
    assert.Equal(t, 0, jsonData.Value)
    assert.Equal(t, 0, gojsonData.Value)
    assert.Equal(t, "Test Description", jsonData.Description)
    assert.Equal(t, "Test Description", gojsonData.Description)
}

The field Value in json is not a int value. The encoding/json fills the Name and Description fields, but goccy/go-json only fills the Name field.

fabionb commented 1 year ago

Did this PR: https://github.com/goccy/go-json/pull/465