H
H
hitakiri2017-07-18 16:16:49
go
hitakiri, 2017-07-18 16:16:49

How to properly convert json to struct?

The server receives a json string from the client:

{
    "progectName": "fgrr",
    "progectDesc": "rgd",
    "progectType": [
        "1",
        "2"
    ],
    "adrFullPath": "w3rw3r",
    "adrInParam": "r3wr",
    "adrOutParam": "fsefse",
    "domains": [
        {
            "key": 1,
            "value": "sefsef"
        }
    ]
}

then the string should be translated into a structure:
type ProgectData struct {
  ProgectName string      `json: "progectName"`
  ProgectDesc string      `json: "progectDesc"`
  ProgectType []string    `json: "progectType"`
  AdrFullPath string      `json: "adrFullPath"`
  AdrInParam  string      `json: "adrInParam"`
  AdrOutParam string      `json: "adrOutParam"`
  Domains     DomainsData `json: "domains"`
}

type DomainsData struct {
  Key   int    `json: "key"`
  Value string `json: "value"`
}

func Dsd(d string) ProgectData {
  text := []byte(d)
  var s ProgectData
  err := json.Unmarshal(text, &s)
  if err != nil {
    CheckErr(err)
  }
  return s
}

This code gives an error:
invalid character 'e' in literal null (expecting 'u')
I found information that this error occurs when the structure and json are combined incorrectly. But I can't find the joint.
PS Thank you very much. DomainsData really needs to be converted to an array. Those. The reason it didn't work was because of the compiler. After reinstalling everything worked fine (i.e. I first checked it on another computer and everything is OK). Domains []DomainsData `json: "domains"`

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Shatokhin, 2017-07-18
@hitakiri

In your json domains, this is the DomainsData array. And in struct it is an instance of DomainsData

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question