Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improving support for structs that are hard to deserialize #8

Merged
merged 5 commits into from
Mar 5, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[FEATURE] We can now deserialize time.Time
Yoric committed Mar 5, 2024
commit 5c4446cd9b00e43fb229810e16d121793c835f15
10 changes: 5 additions & 5 deletions deserialize/deserialize.go
Original file line number Diff line number Diff line change
@@ -491,14 +491,14 @@ func makeStructDeserializerFromReflect(path string, typ reflect.Type, options st
// By Go convention, a field with lower-case name or with a publicFieldName of "-" is private and
// should not be parsed.
isPublic := (*publicFieldName != "-") && fieldNativeExported
if !isPublic && !initializationData.willPreinitialize {
return nil, fmt.Errorf("struct %s contains a field \"%s\" that is not public, you should either make it public or specify an initializer with `Initializer` or `UnmarshalJSON`", path, fieldNativeName)
if !isPublic && !initializationData.willPreinitialize && !wasPreInitialized {
return nil, fmt.Errorf("struct %s contains a field \"%s\" that is not public and not pre-initialized, you should either make it public or specify an initializer with `Initializer` or `UnmarshalJSON`", path, fieldNativeName)
}

fieldPath := fmt.Sprint(path, ".", *publicFieldName)

var fieldContentDeserializer reflectDeserializer
fieldContentDeserializer, err = makeFieldDeserializerFromReflect(fieldPath, fieldType, options, &tags, selfContainer, initializationData.willPreinitialize)
fieldContentDeserializer, err = makeFieldDeserializerFromReflect(fieldPath, fieldType, options, &tags, selfContainer, initializationData.willPreinitialize || wasPreInitialized)
if err != nil {
return nil, err
}
@@ -785,7 +785,7 @@ func makeSliceDeserializer(fieldPath string, fieldType reflect.Type, options sta
subContainer := reflect.New(fieldType).Elem()

// Prepare a deserializer for elements in this slice.
childPreinitialized := tags.IsPreinitialized()
childPreinitialized := wasPreinitialized || tags.IsPreinitialized()
elementDeserializer, err := makeFieldDeserializerFromReflect(arrayPath, fieldType.Elem(), options, &subTags, subContainer, childPreinitialized)
if err != nil {
return nil, fmt.Errorf("failed to generate a deserializer for %s\n\t * %w", fieldPath, err)
@@ -868,7 +868,7 @@ func makePointerDeserializer(fieldPath string, fieldType reflect.Type, options s
elemType := fieldType.Elem()
subTags := tagsPkg.Empty()
subContainer := reflect.New(fieldType).Elem()
childPreinitialized := tags.IsPreinitialized()
childPreinitialized := wasPreinitialized || tags.IsPreinitialized()
elementDeserializer, err := makeFieldDeserializerFromReflect(ptrPath, fieldType.Elem(), options, &subTags, subContainer, childPreinitialized)
if err != nil {
return nil, fmt.Errorf("failed to generate a deserializer for %s\n\t * %w", fieldPath, err)
31 changes: 31 additions & 0 deletions deserialize/deserialize_test.go
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ import (
"fmt"
"strings"
"testing"
"time"

"github.com/pasqal-io/godasse/deserialize"
jsonPkg "github.com/pasqal-io/godasse/deserialize/json"
@@ -1199,3 +1200,33 @@ func TestSupportBothUnmarshalerAndDictInitializer(t *testing.T) {
}

// -----

// ----- Test that we can deserialize a struct witha field that should not be deserializable if we have some kind of pre-initializer.

type StructWithTime struct {
Field time.Time `initialized:"true"`
Field2 StructWithTimeInitializer
}

type StructWithTimeInitializer struct {
Field time.Time
}

func (*StructWithTimeInitializer) Initialize() error {
return nil
}

func TestDeserializingWithPreinitializer(t *testing.T) {
date := time.Date(2000, 01, 01, 01, 01, 01, 01, time.UTC)
sample := StructWithTime{
Field: date,
Field2: StructWithTimeInitializer{
Field: date,
},
}
result, err := twoWays[StructWithTime](t, sample)
assert.NilError(t, err)
assert.DeepEqual(t, result, &sample)
}

// ------
24 changes: 19 additions & 5 deletions deserialize/json/json.go
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
package json

import (
"encoding"
"encoding/json"
"errors"
"fmt"
@@ -141,13 +142,26 @@ func (u Driver) Unmarshal(in any, out *any) (err error) {

// Attempt to deserialize as a `json.Unmarshaler`.
if unmarshal, ok := (*out).(json.Unmarshaler); ok {
return unmarshal.UnmarshalJSON(buf) //nolint:wrapcheck
err = unmarshal.UnmarshalJSON(buf)
} else {
err = json.Unmarshal(buf, out)
}
err = json.Unmarshal(buf, out)
if err != nil {
return fmt.Errorf("failed to unmarshal '%s': \n\t * %w", buf, err)
if err == nil {
// Basic JSON decoding worked, let's go with it.
return nil
}
return nil
// But sometimes, things aren't that nice. For instance, time.Time serializes
// itself as an unencoded string, but its UnmarshalJSON expects an encoded string.
// Just in case, let's try again with UnmarshalText.
if textUnmarshaler, ok := (*out).(encoding.TextUnmarshaler); ok {
err2 := textUnmarshaler.UnmarshalText(buf)
if err2 == nil {
// Success! Let's use that result.
return nil
}
return fmt.Errorf("failed to unmarshal '%s' either from JSON or from text: \n\t * %w\n\t * and %w", buf, err, err2)
}
return fmt.Errorf("failed to unmarshal '%s': \n\t * %w", buf, err)
}

func (u Driver) WrapValue(wrapped any) shared.Value {