Skip to content

Unmarshal of object/struct attributes fails #74

Open
@gopherfortress

Description

@gopherfortress

Hello,

I am trying to unmarshal a JSON API response which contains attributes that are objects. I tried marshaling and the result JSON is correct but when I try to unmarshal that same JSON it fails with data is not a jsonapi representation of '*main.Profile'. Here is some example code:

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/google/jsonapi"
)

func main() {
	p := &Profile{ID: "1", Avatar: &Avatar{Large: "url1", Small: "url2"}}
	buf := &bytes.Buffer{}
	if err := jsonapi.MarshalOnePayload(buf, p); err != nil {
		log.Fatal(err)
	}

	p = &Profile{}
	fmt.Println(string(buf.Bytes()))
	err := jsonapi.UnmarshalPayload(buf, p)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("ID: %v, Avatar:%v\n", p.ID, p.Avatar)
}

type Profile struct {
	ID     string  `json:"id" jsonapi:"primary,profiles"`
	Avatar *Avatar `json:"avatar" jsonapi:"attr,avatar"`
}

type Avatar struct {
	Large string `json:"large"`
	Small string `json:"small"`
}

I also tried annotating with attr like

type Avatar struct {
	Large string `json:"large" jsonapi:"attr,large,omitempty"`
	Small string `json:"small" jsonapi:"attr,small,omitempty"`
}

but no luck.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions