Home > Software engineering >  How to map the nested field in a collection to go struct that is not nested in format?
How to map the nested field in a collection to go struct that is not nested in format?

Time:09-17

Format of bson:

{
  name: "root", 
  sports:" Cricket", 
  Personal: {
     age:32
  }
}

Go struct format:

type Person struct {
    Name string `bson:"name"`
    Age  int `bson:"age"`
}

How to bind the value of age into this struct format in golang?

CodePudding user response:

You need an intermediate type that will help you transform your database DTO (Data Transform Object) into model object. It is recommended to separate those two.

package main

import (
    "encoding/json"
    "fmt"
)

type PersonInfoDto struct {
    Age int `json:"age"`
}

type PersonDto struct {
    Name     string        `json:"name"`
    Sports   string        `json:"sports"`
    Personal PersonInfoDto `json:"Personal"`
}

type Person struct {
    Name string
    Age  int
}

func main() {
    jsonInput := "{ \"name\": \"root\", \"sports\": \"Cricket\", \"Personal\": { \"age\": 32 }}"
    var dto PersonDto
    err := json.Unmarshal([]byte(jsonInput), &dto)
    if err != nil {
        fmt.Println(err)
    }

    // your model object
    p := Person{dto.Name, dto.Personal.Age}
    fmt.Println(p)
}

  • Related