0

I have a need to unmarshal a json object that has values that can change. A typical object would have as an example the following properties defined:

{
    "entityName": "example Property",
    "properties": [
        {
            "name": "property1",
            "type": "string",
            "value": "Test Value"
        },
        {
            "name": "property2",
            "type": "float",
            "value": "12.5"
        },
        {
            "name": "property3",
            "type": "integer",
            "value": 1
        }
    ]
}

Each property would declare itself as the type it would need to be unmarshalled to. I have solved this problem in Java using generics but I am unsure, how I would declare my object in Go?

Charles Bryant
  • 995
  • 2
  • 18
  • 30

1 Answers1

0

In go you would you the JSON library to parse the JSON-encoded data into a struct. So for your example let's say you are getting your data from a webpage.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "io/ioutil"
)

type Payload struct {
    EntityName string
    properties Properties
}

type Properties struct{
    name string
    type string
    value string

}


func main() {
    url := "some site where data is stored"
    res, err  := http.Get(url)
    if err != nil {
        panic (err)
    } 
    defer res.Body.Close()

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err)
    }

    var p Payload

    err = json.Unmarshal(body, &p)
    if err != nil{
       panic (err)
    }

    fmt.Println(p.EntityName\n, p.properties)
}

This is by no means an efficient or smart way of doing this, I just quickly hacked this together. But I hope it conveys the concept.