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

Failed to unmarshal while "encoding/json" is working fine #228

Closed
susuper opened this issue May 19, 2021 · 2 comments · Fixed by #229
Closed

Failed to unmarshal while "encoding/json" is working fine #228

susuper opened this issue May 19, 2021 · 2 comments · Fixed by #229

Comments

@susuper
Copy link
Sponsor

susuper commented May 19, 2021

The following code is working fine with "encoding/json" (msg fields are propagated after unmarshal). Unfortunately the "github.com/goccy/go-json" is unable to unmarshal.

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Message struct {
	ChannelID   int64
	Data        json.RawMessage
	ChannelName string
	Pair        string
	Sequence    Seq
}

type Seq struct {
	Value int64 `json:"sequence"`
}

func (msg *Message) UnmarshalJSON(data []byte) error {
	var raw []json.RawMessage
	if err := json.Unmarshal(data, &raw); err != nil {
		return err
	}

	if len(raw) < 3 {
		return fmt.Errorf("invalid data length: %#v", raw)
	}

	body := make([]interface{}, 0)
	if len(raw) == 3 {
		body = append(body, &msg.Data, &msg.ChannelName, &msg.Sequence)
	}

	body = append(body, &msg.ChannelID, &msg.Data, &msg.ChannelName, &msg.Pair)

	return json.Unmarshal(data, &body)
}

func main() {
	data := []byte(`[4688,{"as":[["28.15860","100.00000000","1621372849.562940"]],"bs":[["28.13020","1.28798426","1621372848.211647"]]},"book-10","DOT/GBP"]`)

	var msg Message
	if err := json.Unmarshal(data, &msg); err != nil {
		fmt.Printf("error while unmarshaling JSON: %v", err)

		os.Exit(0)
	}

	fmt.Printf("Channel name is %s", msg.ChannelName)
}

Go Playground

Thank you for your work!

@goccy
Copy link
Owner

goccy commented May 19, 2021

Thank you for the great reporting ! ( and Thank you for being a sponsor ! )
Probably, I fixed this issue with #229

@susuper
Copy link
Sponsor Author

susuper commented May 21, 2021

Thank you, it works now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants