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

json.Unmarshal is nil #2

Open
ymzuiku opened this issue Jul 22, 2022 · 2 comments
Open

json.Unmarshal is nil #2

ymzuiku opened this issue Jul 22, 2022 · 2 comments

Comments

@ymzuiku
Copy link

ymzuiku commented Jul 22, 2022

I very like this repo, but it's confused me.

This's a use safetypes's struct

type Dog struct {
	Name  Option[string] `json:"name,omitempty"`
}

json.Unmarshal input json:

{"name":"hello"}

it get: Dog{Name:nil}

If in the rust, input json:

{"name":"hello"}

rust get like: Dog{Name:Option("hello")}


Ok, I now Option is struct { Value: *T }, bug frontend developer don't like {"name":{"value":"hello"}}.

I can use flat fn, flat server response, delete *value:

func flatOptionValue(target any) {
	if data, ok := target.(map[string]any); ok {
		for key, item := range data {
			if m, ok := item.(map[string]any); ok {
				if v, ok := m["value"]; ok && len(m) == 1 {
					data[key] = v
					flatOptionValue(v)
					continue
				}
				flatOptionValue(m)
			}
		}
	} else if arr, ok := target.([]any); ok {
		for _, v := range arr {
			flatOptionValue(v)
		}
	}
}

But I can't json.Unmarshal the {"name":"hello"} json to struct.

@eminarican
Copy link
Owner

okay i'll look into it

@eminarican
Copy link
Owner

@ymzuiku latest commit should fix the problem could you test it?

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

No branches or pull requests

2 participants