@oleg5896

Как распарсить json в массив структур golang (gin)?

Есть json, который приходит на сервер gin
{
"test_2407811386": 
{"nativeId":"2407811386","source":"test","url":"https://test.ru/123","title":"TEST»","price":"123"},
"test_2415474304":
{"nativeId":"2415474304","source":"test","url":"https://test/234","title":"TEST2»","price":"234"}
}


Есть структуры:
type Object struct {
	Key   string
	Value Params
}

type Params struct {
	NativeId string `json:"nativeId"`
	Source   string `json:"source"`
	Url      string `json:"url"`
	Title    string `json:"title"`
	Price    string `json:"price"`
}


Пробовал с помощью BindJSON, не получилось

Еще пробовал вот так:
func (h *Handler) checkList(c *gin.Context) {
	var objects []server.Object
	jsonDataBytes, _ := ioutil.ReadAll(c.Request.Body)
	if err := json.Unmarshal(jsonDataBytes, &objects); err != nil {
		newErrorResponse(c, http.StatusBadRequest, err.Error())
		return
	}
}

Прошу помощи так как в Go пришел из php совсем недавно
  • Вопрос задан
  • 530 просмотров
Решения вопроса 1
EvgenyMamonov
@EvgenyMamonov Куратор тега Go
Senior software developer, system architect
Можно через map[string]Params
Например вот так
package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Params struct {
    NativeId string `json:"nativeId"`
    Source   string `json:"source"`
    Url      string `json:"url"`
    Title    string `json:"title"`
    Price    string `json:"price"`
}

func main() {
    jsonDataBytes := []byte(`{
        "test_2407811386": {"nativeId":"2407811386","source":"test","url":"https://test.ru/123","title":"TEST»","price":"123"},
        "test_2415474304": {"nativeId":"2415474304","source":"test","url":"https://test/234","title":"TEST2»","price":"234"}
    }`)
    objects := map[string]Params{}
    err := json.Unmarshal(jsonDataBytes, &objects)
    if err != nil {
        log.Fatalf("unmarshal error: %s\n", err.Error())
    }
    fmt.Printf("%v\n", objects)
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы