Fix ID fields to accept both JSON strings and numbers

The Yandex Music API returns IDs as both JSON strings and numbers depending
on the endpoint. Added JSONID custom type in internal/models/base.go that
implements json.Unmarshaler to accept both formats and store as string.

Changed ID fields from string to JSONID:
- Track.ID, Major.ID, TrackLyricsInfo.ID (track.go)
- Album.ID, TrailerInfo.TrackID, TrailerInfo.AlbumID (album.go)

Updated example to convert JSONID to string when passing to client methods.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
MrixsandClaude Code committed 2026-10-18 10:21:58 +03:00
1 parent 0456ca0665
commit 5535d2a941
4 files changed
+49 -20

No files matched your search

+29
View File
@@ -4,6 +4,8 @@ package models
import (
"encoding/json"
"fmt"
"strconv"
"gitea.mrixs.me/Mrixs/yandex-music-api-go/internal/utils"
)
@@ -81,3 +83,30 @@ func (b *BaseModel) SetClient(c ClientInterface) {
func (b *BaseModel) GetClient() ClientInterface {
return b.Client
}
// JSONID is an ID that can be represented as either a JSON string or a JSON number.
// The Yandex Music API sometimes returns IDs as numbers (e.g., 12345) and sometimes
// as strings (e.g., "12345"). JSONID accepts both and stores the value as a string.
type JSONID string
// UnmarshalJSON implements json.Unmarshaler, accepting both JSON strings and numbers.
func (id *JSONID) UnmarshalJSON(data []byte) error {
// Try string first
var s string
if err := json.Unmarshal(data, &s); err == nil {
*id = JSONID(s)
return nil
}
// Try number (float64 is the default JSON number decoding)
var f float64
if err := json.Unmarshal(data, &f); err != nil {
return fmt.Errorf("cannot unmarshal %v into JSONID: %w", string(data), err)
}
*id = JSONID(strconv.FormatFloat(f, 'f', -1, 64))
return nil
}
// String returns the ID as a Go string.
func (id JSONID) String() string {
return string(id)
}