Created
August 20, 2019 09:27
-
-
Save locona/366c2499515a77848353c42cf1675f4b to your computer and use it in GitHub Desktop.
How to change to json string without escaping.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type IDType struct { | |
Value int | |
Valid bool | |
} | |
type Parent struct { | |
ID interface{} `json:"id"` | |
SomeString string `json:"some_string"` | |
} | |
func (parent *Parent) MarshalJSON() ([]byte, error) { | |
// var ii interface{} | |
// json.Unmarshal(&parent.ID, &ii) | |
// fmt.Println(ii) | |
ss := json.RawMessage(fmt.Sprintf("%v", parent.ID)) | |
type Alias Parent | |
return json.Marshal(struct { | |
*Alias | |
ID interface{} `json:"id"` | |
}{ | |
Alias: (*Alias)(parent), | |
ID: &ss, | |
}) | |
} | |
func main() { | |
id := &IDType{Value: 1, Valid: true} | |
b, _ := json.Marshal(id) | |
fmt.Println(string(b)) | |
parent := &Parent{ID: string(b), SomeString: "Hello"} | |
bb, _ := json.Marshal(parent) | |
fmt.Println(string(bb)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment