Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
680 B
2
Indexable
Never
package main

import (
    "encoding/json"
    "fmt"
)

type MyStruct struct {
    A string `json:"A,omitempty"`
    B *string `json:"B"`
}

func (s MyStruct) MarshalJSON() ([]byte, error) {
    type Alias MyStruct
    if s.A == "" {
        return json.Marshal(&struct {
            *Alias
            B *string `json:"B,omitempty"`
        }{Alias: (*Alias)(&s)})
    }
    return json.Marshal(&struct {
        *Alias
    }{Alias: (*Alias)(&s)})
}

func main() {
    myData := MyStruct{
        A: "",
        B: stringPointer("ValorB"),
    }

    jsonData, _ := json.Marshal(myData)
    fmt.Println(string(jsonData))
}

func stringPointer(s string) *string {
    return &s
}