Skip to content
This repository was archived by the owner on Sep 4, 2025. It is now read-only.

Marshal nested object does not workΒ #207

@SkYNewZ

Description

@SkYNewZ

In a third party library that uses this library, I have an error because marshaling a nested object does not work.

So I take the opportunity to post an issue here as well.
You can see an example test file which demonstrate this issue.

main.go
// main.go
package main

import (
	"bytes"

	"github.com/google/jsonapi"
)

// Nested describes a nested object
type Nested struct {
	Name *string `jsonapi:"attr,name"`
}

// Object is the main example object
type Object struct {
	Type         string  `jsonapi:"primary,object"`
	Color        *string `jsonapi:"attr,color"`
	Enable       *bool   `jsonapi:"attr,enable"`
	NestedObject *Nested `jsonapi:"attr,nested-object"`
}

func MarshalNestedObject() (string, error) {
	n := new(Nested)
	n.Name = toStringPtr("foo")

	var b bytes.Buffer
	err := jsonapi.MarshalPayload(&b, n)
	return b.String(), err
}

func MarshalObject() (string, error) {
	n := new(Nested)
	n.Name = toStringPtr("foo")

	o := &Object{
		Color:        toStringPtr("blue"),
		Enable:       toBoolPtr(true),
		NestedObject: n,
	}

	var b bytes.Buffer
	err := jsonapi.MarshalPayload(&b, o)
	return b.String(), err
}

func toStringPtr(in string) (out *string) {
	out = &in
	return
}

func toBoolPtr(in bool) (out *bool) {
	out = &in
	return
}
main_test.go
// main_test.go
package main

import (
	"reflect"
	"testing"
)

func TestMarshalNestedObject(t *testing.T) {
	tests := []struct {
		name    string
		want    string
		wantErr bool
	}{
		{
			name: "expected",
			want: `{"data":{"type":"","attributes":{"name":"foo"}}}
`,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := MarshalNestedObject()
			if (err != nil) != tt.wantErr {
				t.Errorf("MarshalNestedObject() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("MarshalNestedObject() got = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestMarshalObject(t *testing.T) {
	tests := []struct {
		name    string
		want    string
		wantErr bool
	}{
		{
			name: "expected",
			want: `{"data":{"type":"object","attributes":{"color":"blue","enable":true,"nested-object":{"name":"foo"}}}}
`,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := MarshalObject()
			if (err != nil) != tt.wantErr {
				t.Errorf("MarshalObject() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("MarshalObject() got = %v, want %v", got, tt.want)
			}
		})
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions