[英]How can i add set of information (in user defined data type) to an Array in java
[英]how can I defined this type data in golang
我有一個像'{"{\\"hello\\":\\"world\\"}"}'
這樣的數據,它是 postgresql 中的數組 json。
我不知道如何在 golang 中處理它。 我知道我可以用string
定義然后使用json.Unmarshal
來json.Unmarshal
,但我想知道是否有辦法將它放入struct
我假設你發布了不正確的 JSON,假設它是'{"hello": "world"}
一個結構體有一個預定義的字段,並且任意 JSON 進入它是不可能提前知道的。 可能的解決方案是將其轉換為地圖。
var data interface{}
b := []byte(`{"hello": "world"}`)
err := json.Unmarshal(b, &data)
if err != nil {
panic(err)
}
fmt.Print(data)
當您打印出數據時,您可能會得到類似的信息。 map[hello:world]
它采用map[string]interface{}
。
然后,您可以使用 type switch 循環進入地圖結構,直到您輸入 assert all the interface{}
。
for k, v := range data.(map[string]interface{}) {
switch val := v.(type) {
case string:
v = val
default:
fmt.Println(k, "is unknown type")
}
}
在處理任意傳入的 JSON 時,Map 是一種理想的數據結構。 但是,如果 JSON 是從具有預定義架構的 SQL 表生成的,則您可以使用具有相同結構的結構而不是映射。
type Hello struct {
Hello string `json:"hello"`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.