Dynamic Object creation on Unmarshalling JSON

I am trying to dynamically create and invoke a common method after parsing JSON file. The JSON file has an array of “vehicle Types”

{
    "vehicle": [
            "car",
            "truck",

    ]
  }
}

type car struct {}
type truck struck {}

type driveInterface interface {
  drive() 
}

func (car) drive {
    fmt.Println("Driving Car")
}

 

func (truck) drive {
    fmt.Println("Driving truck")
}

Here a sample

package main

import (
“fmt”
)

type driveInterface interface {
drive()
}

type car struct {
license string
owner string
}

func (c car) drive() {
fmt.Printf(“Driving Car”)
}

type truck struct {
license string
driver string
wheels int
}

func (t truck) drive() {
fmt.Println(“Driving truck”)
}

func showVehicles(vehicles []driveInterface) {
for _, vehicle := range vehicles {
vehicle.drive()
}
}

func main() {
car1 := car{“1”, “Donald Duck”}
car2 := car{“2”, “Mickey Mouse”}

truck1 := truck{"4", "John", 8}
truck2 := truck{"5", "Jane", 6}

vehicles := []driveInterface{car1, car2, truck1, truck2}
showVehicles(vehicles)

}

I think this is what you’re looking for: https://play.golang.org/p/b0T5xm_MGfc

There may be other (maybe “better”) ways to do this, but I see JSON as a temporary serialization encoding format and if you need to encode something more than “plain ol’ data”, then you need helper functions to translate that data into the proper types.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.