2017-03-21 3 views
1

Je crée une fonction pour obtenir un tableau d'objet et l'enregistrer dans Struct. Ensuite, je veux le convertir en JSON.Ajouter des clés avant json.Marshal dans Golang

func GetCountry(msg string) []byte { 
    var countries []*countryModel.Country 

    countries = countryModel.GetAllCountry() 

    jsResult, err := json.Marshal(countries) 

    if err != nil { 
     logger.Error(err, "Failed on GetCountry") 
    } 

    return jsResult 
} 

Voici le struct

type Country struct { 
    Id   int `json:"id"` 
    CountryCode string `json:"country_code"` 
    CountryName string `json:"country_name"` 
    PhoneCode string `json:"phone_code"` 
    Icon   string `json:"icon"` 
} 

Avec cette fonction, je reçois ces résultats

[ 
    { 
    "id": 2, 
    "country_code": "MY", 
    "country_name": "Malaysia", 
    "phone_code": "+60", 
    "icon": "no-data" 
    }, 
    { 
    "id": 2, 
    "country_code": "MY", 
    "country_name": "Malaysia", 
    "phone_code": "+60", 
    "icon": "no-data" 
    } 
] 

Comment puis-je ajouter une clé nommée 'pays' pour ce résultat JSON? Ces ce que je suis attendre

{ 
    "countries" : 
     [ 
      { 
      "id": 2, 
      "country_code": "MY", 
      "country_name": "Malaysia", 
      "phone_code": "+60", 
      "icon": "no-data" 
      }, 
      { 
      "id": 2, 
      "country_code": "MY", 
      "country_name": "Malaysia", 
      "phone_code": "+60", 
      "icon": "no-data" 
      } 
     ] 
} 

S'il vous plaît aider

Répondre

1

Vous pouvez créer une structure d'emballage qui contient un tableau de struct de pays, avec json: "countries" après la déclaration du tableau des pays, puis appelez json.Marshal sur l'emballage .

à quoi il ressemble:

type CountryWrapper struct { 
    Countries []*countryModel.Country `json: "countries"` 
} 

Ensuite, dans votre méthode, instancier comme CountryWrapper{ Countries: countries } et appeler json.Marshal sur cet objet.