safetypes icon indicating copy to clipboard operation
safetypes copied to clipboard

json.Unmarshal is nil

Open ymzuiku opened this issue 1 year ago • 2 comments

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.

ymzuiku avatar Jul 22 '22 17:07 ymzuiku