0

Im working with the API with possibile output:

[
 {
  "contactId": 2,
  "email": "karina.plain@example.com",
  "markerName": "JavascriptEngine",
  "dataType": "String",
  "value": "Carakan",
  "dateEntered": "2013-01-03T14:52:00"
 },
{
  "contactId": 2,
  "email": "karina.plain@example.com",
  "markerName": "HasReadEntireMessage",
  "dataType": "Boolean",
  "value": true,
  "dateEntered": "2013-01-03T18:02:00"
 }]

I have a problem with "value. "What should a struct look like, that will allow this JSON to be unmarshal to its array?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
R.Slaby
  • 349
  • 2
  • 4
  • 10

2 Answers2

2

Since it seems possible for the value of the "value" key to be of any type, you should use the type interface{} for this field. This is the empty interface, which matches any type that implements at least zero methods, which is any type.

So you can use the type:

type Contact struct {
    ContactId   int         `json:"contactId"`
    Email       string      `json:"email"`
    MarkerName  string      `json:"markerName"`
    DataType    string      `json:"dataType"`
    Value       interface{} `json:"value"`
    DateEntered string      `json:"dateEntered"`
}

See this working example.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
-1
type Template []struct {
    ContactID   int    `json:"contactId"`
    Email       string `json:"email"`
    MarkerName  string `json:"markerName"`
    DataType    string `json:"dataType"`
    Value       string `json:"value"`
    DateEntered string `json:"dateEntered"`
}

Or

type Template []struct {
    ContactID   int    `json:"contactId"`
    Email       string `json:"email"`
    MarkerName  string `json:"markerName"`
    DataType    string `json:"dataType"`
    Value       bool   `json:"value"`
    DateEntered string `json:"dateEntered"`
}
ABC
  • 2,068
  • 1
  • 10
  • 21