John Balvin Arias
John Balvin Arias

Reputation: 2896

Can´t unmarshal json to an exported struct from other package

I wan´t to unmarshal json to an exported struct from other package but I does not work propertly

package anyPackage

type DataStruct struct{
    Size     int    `json:"size"`
    Material string `json:"material"`
    Date     time.Time
}

package main

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

type NewStruct struct{
    Name      string `json:"name"`
    Code      int    `json:"code"`
    ExtraData anyPackage.DataStruct
}

func main(){
    blob := `{ "name":"John", "code":12546, "material":"wood","size":456 }`

    var aux NewStruct
    if err := json.Unmarshal([]byte(blob), &aux); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v", aux)
}

In that case, name and code are correctly unmarshal, but material and size don´t, they are empty

Upvotes: 0

Views: 400

Answers (2)

mkopriva
mkopriva

Reputation: 38313

You should be able to fix the issue by embedding the DataStruct instead of having a separate field.

type NewStruct struct{
    Name string `json:"name"`
    Code int    `json:"code"`
    anyPackage.DataStruct
}

Upvotes: 5

Adrian
Adrian

Reputation: 46562

The fact that the type is in another package is irrelevant to unmarshalling JSON. The problem is that your data structure doesn't match the JSON. Your structure is effectively:

struct {
    Name string `json:"name"`
    Code int `json:"code"`
    ExtraData struct {
        Size int `json:"size"`
        Material string `json:"material"`
        Date time.Time
    }
}

Which would equate to JSON like:

{
    "name":"John",
    "code":12546,
    "ExtraData": {
        "material":"wood",
        "size":456
    }
}

But that is not your JSON structure. Either your data structure or your JSON needs to be modified such that they match.

Upvotes: 5

Related Questions