-
Notifications
You must be signed in to change notification settings - Fork 87
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 Marshal error on generated empty OptString
struct
#660
Comments
OptString
struct
Encoding and decoding with So it is impossible to represent |
@ernado thanks for the quick response, so how should I deal with it, can I omit OptString and use pointers as most other generators do? |
Looks like just handling zeroed value works Would it be a case to just do PR to the generator for // MarshalJSON implements stdjson.Marshaler.
func (s OptString) MarshalJSON() ([]byte, error) {
if !s.Set {
return []byte(`{}`), nil
}
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
Just is there a way to check if Type is optional in template? |
What are you trying to do? Using Returning |
I try to send generated struct through external library (NATS) and don't have control over marshaller. Additional info: Fields are not initialized. |
It's more about generating valid JSON - as looks like currently, we're ending with something like |
I see there several ways to fix it:
|
@tdakkota |
The only valid solution is (1). Let's remove |
Maybe just make no 1 optional? To not break possible existing implementations |
Hi, for objects workaround with overhead ...
// use generated method MarshalJSON.
tempBts, err := s.MarshalJSON()
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
var m map[string]interface{}
// unmarshal to map[string]interface{}
if er := json.Unmarshal(tempBts, &m); er != nil {
return fmt.Errorf("umarshal to map: %w", er)
}
// use std MarshalIndent for get ident json.
bts, err := json.MarshalIndent(m, "", " ")
if err != nil {
return fmt.Errorf("marshal: %w", err)
} P.S. If all of the Opt fields filled, error not happen! |
Just checking, is this still being worked on?
But they did recently add omitzero in golang/go#45669
Wouldn't this alter data if the structs do have values? Is this all because of avoiding pointers? |
Yes, we avoid pointers for better semantics and removing NPE problem. Will use |
What version of ogen are you using?
v0.54.1
Can this issue be reproduced with the latest version?
Yes just try to run this test in directory where API is generated with OptString
So for most use cases with fields set to not required when trying to marshal it (e.g. send through event bus) it's not possible to use ogen.
Getting output:
The text was updated successfully, but these errors were encountered: