diff --git a/node.go b/node.go index 1e722e8..22f5efe 100644 --- a/node.go +++ b/node.go @@ -23,7 +23,7 @@ type ManyPayload struct { // Node is used to represent a generic JSON API Resource type Node struct { Type string `json:"type"` - ID string `json:"id"` + ID string `json:"id,omitempty"` ClientID string `json:"client-id,omitempty"` Attributes map[string]interface{} `json:"attributes,omitempty"` Relationships map[string]interface{} `json:"relationships,omitempty"` diff --git a/response_test.go b/response_test.go index 331023e..ba4a142 100644 --- a/response_test.go +++ b/response_test.go @@ -196,6 +196,32 @@ func TestMarshalIDPtr(t *testing.T) { } } +func TestMarshalOnePayload_omitIDString(t *testing.T) { + type Foo struct { + ID string `jsonapi:"primary,foo"` + Title string `jsonapi:"attr,title"` + } + + foo := &Foo{Title: "Foo"} + out := bytes.NewBuffer(nil) + if err := MarshalOnePayload(out, foo); err != nil { + t.Fatal(err) + } + + var jsonData map[string]interface{} + if err := json.Unmarshal(out.Bytes(), &jsonData); err != nil { + t.Fatal(err) + } + payload := jsonData["data"].(map[string]interface{}) + + // Verify that empty ID of type string gets omitted. See: + // https://github.com/google/jsonapi/issues/83#issuecomment-285611425 + _, ok := payload["id"] + if ok { + t.Fatal("Was expecting the data.id member to be omitted") + } +} + func TestMarshall_invalidIDType(t *testing.T) { type badIDStruct struct { ID *bool `jsonapi:"primary,cars"`