【问题标题】:Golang elegantly JSON decode different structuresGolang 优雅地 JSON 解码不同的结构
【发布时间】:2017-12-20 17:13:57
【问题描述】:

我有不同的结构共享一个字段,我需要在 Go 中将 JSON 文件解码为其对应的结构。

例子:

type Dog struct {
  AnimalType string //will always be "dog"
  BarkLoudnessLevel int
}

type Cat struct {
  AnimalType string //will always be "cat"
  SleepsAtNight bool
}

如果我将这些结构之一作为 JSON 字符串接收,将其解析为正确结构的最优雅的方法是什么?

【问题讨论】:

标签: json parsing go


【解决方案1】:

因此,有几种方法可以做到这一点,但最简单的方法可能是将有效负载反序列化两次,并根据有效负载中的“AnimalType”属性进行条件分支。下面是一个使用中间反序列化模型的简单示例:

package main

import (
  "fmt"
  "encoding/json"
)

type Dog struct {
  AnimalType string //will always be "dog"
  BarkLoudnessLevel int
}

type Cat struct {
  AnimalType string //will always be "cat"
  SleepsAtNight bool
}

var (
  payloadOne = `{"AnimalType":"dog","BarkLoudnessLevel":1}`
  payloadTwo = `{"AnimalType":"cat","SleepsAtNight":false}`
)

func main() {
  parseAnimal(payloadOne)
  parseAnimal(payloadTwo)
}

func parseAnimal(payload string) {
  animal := struct{
    AnimalType string
  }{} 
  if err := json.Unmarshal([]byte(payload), &animal); err != nil {
    panic(err)
  }
  switch animal.AnimalType {
  case "dog":
    dog := Dog{}
    if err := json.Unmarshal([]byte(payload), &dog); err != nil {
      panic(err)
    }
    fmt.Printf("Got a dog: %v\n", dog)
  case "cat":
    cat := Cat{}
    if err := json.Unmarshal([]byte(payload), &cat); err != nil {
      panic(err)
    }
    fmt.Printf("Got a cat: %v\n", cat)
  default:
    fmt.Println("Unknown animal")
  }
}

看到它在行动here


IMO 解决此问题的更好方法是将有效负载的“元数据”移动到父结构中,尽管这需要修改预期的 json 有效负载。因此,例如,如果您正在使用如下所示的有效负载:

{"AnimalType":"dog", "Animal":{"BarkLoudnessLevel": 1}}

然后您可以使用json.RawMessage 之类的东西来部分解析结构,然后根据需要有条件地解析其余部分(而不是对所有内容进行两次解析)——也可以更好地分离结构属性。以下是您如何执行此操作的示例:

package main

import (
    "encoding/json"
    "fmt"
)

type Animal struct {
    AnimalType string
    Animal     json.RawMessage
}

type Dog struct {
    BarkLoudnessLevel int
}

type Cat struct {
    SleepsAtNight bool
}

var (
    payloadOne = `{"AnimalType":"dog", "Animal":{"BarkLoudnessLevel": 1}}`
    payloadTwo = `{"AnimalType":"cat", "Animal":{"SleepsAtNight": false}}`
)

func main() {
    parseAnimal(payloadOne)
    parseAnimal(payloadTwo)
}

func parseAnimal(payload string) {
    animal := &Animal{}
    if err := json.Unmarshal([]byte(payload), &animal); err != nil {
        panic(err)
    }
    switch animal.AnimalType {
    case "dog":
        dog := Dog{}
        if err := json.Unmarshal(animal.Animal, &dog); err != nil {
            panic(err)
        }
        fmt.Printf("Got a dog: %v\n", dog)
    case "cat":
        cat := Cat{}
        if err := json.Unmarshal(animal.Animal, &cat); err != nil {
            panic(err)
        }
        fmt.Printf("Got a cat: %v\n", cat)
    default:
        fmt.Println("Unknown animal")
    }
}

在行动here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多