A
A
Andrey2018-02-22 19:18:59
go
Andrey, 2018-02-22 19:18:59

How to correctly expand json of an arbitrary structure?

Hello.
There is a task.
There is a queue into which tasks of different types are poured, which are uniquely pointed to by the alias property in the json task.
The task also contains the data property, which contains the task's guid, and the properties field, which contains an arbitrary object required to process the task.
Is this code normal for parsing json? Naturally, in the future, data structures, in addition to the global Task, will move to separate files along with the logic for processing them.

package main

import (
  "encoding/json"
  "fmt"
)

type Task struct {
  Alias string
}

type FootballTaskDataProperties struct {
  A int
  B int
  C int
  D int
}

type FootballTaskData struct {
  Guid       string
  Properties FootballTaskDataProperties
}

type FootballTask struct {
  Alias string
  Data  FootballTaskData
}

func main() {

  var item Task

  var jsonData = []byte(`{"alias":"football", "data": {"guid":"0aeaa197-44f5-4f73-a179-982cd2f0a52d", "properties": {"a":1,"b":97,"c":5,"d":0}, "Version":"4.7.1471"}}`)

  err := json.Unmarshal(jsonData, &item)

  if err != nil {
    fmt.Println("error:", err)
  }

  switch item.Alias {
  case "football":

    var currentStruct FootballTask

    json.Unmarshal(jsonData, &currentStruct)

    fmt.Printf("\n%+v", currentStruct)
    fmt.Print(currentStruct.Data.Properties.A)
  }
}

Thank you for reading this code to the end :-)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-02-22
@VladimirAndreev

You only change Properties , it might be worth writing one structure in which the changing parameter is designated as interface{} or map[string]interface{}, and then, when processing tasks, bring this value into the proper form

type Task struct {
  Alias string `json:"alias"`
  Data  struct {
    GUID       string `json:"guid"`
    Properties map[string]interface{} `json:"properties"`
    Version string `json:"Version"`
  } `json:"data"`
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question