du6jws6975 2018-07-16 09:39
浏览 323

Golang json根据键值对解组

I have json as following

"data": [
    {
        "id": "recent_search",
        "items": [],
        "name": ""
    },
    {
        "id": "popular_search",
        "items": [],
        "name": ""
    },
    {
        "id": "digital",
        "items": [],
        "name": "DIGITAL"
    }
]

and the structs are as follows:

type universeTypeData struct {
Recent       universeSearchInfo 
Popular      universeSearchInfo 
Digital      universeSearchInfo 
}

type universeSearchInfo struct {
ID    string               `json:"id"`
Name  string               `json:"name"`
Items []universeSearchItem `json:"items"`
}

I want to unmarshal my json as "id" with value "recent_search" map to Recent, "id" with value "popular_search" map to Popular. Is there any way of doing this in golang?

My approach of doing it is

for _, v := range result.Data {
    if v.ID == "in_category" {
        finalResult.Universe.InCategory.ID = v.ID
        finalResult.Universe.InCategory.Name = v.Name
        for _, abc := range v.Items {
            finalResult.Universe.InCategory.Items = append(finalResult.Universe.InCategory.Items, abc)
        }
    }
    if v.ID == "recent_search" {
        finalResult.Universe.Recent.ID = v.ID
        finalResult.Universe.Recent.Name = v.Name
        for _, abc := range v.Items {
            finalResult.Universe.Recent.Items = append(finalResult.Universe.Recent.Items, abc)
        }
    }
    if v.ID == "popular_search" {
        finalResult.Universe.Popular.ID = v.ID
        finalResult.Universe.Popular.Name = v.Name
        for _, abc := range v.Items {
            finalResult.Universe.Popular.Items = append(finalResult.Universe.Popular.Items, abc)
        }
    }

Is there any better way of doing it?

  • 写回答

2条回答 默认 最新

  • dongzhao8233 2018-07-16 10:39
    关注

    Implement Unmarshaler interface:

    Unmarshaler is the interface implemented by types that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.

    json unmarshaler interface assign the value from json to struct after parsing the result and applying conditions to fetch the value.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Details struct {
        Data []universeSearchInfo `json:"data"`
    }
    
    type universeTypeData struct {
        Recent  universeSearchInfo
        Popular universeSearchInfo
        Digital universeSearchInfo
    }
    
    type universeSearchInfo struct {
        ID    string   `json:"id"`
        Name  string   `json:"name"`
        Items []string `json:"items"`
    }
    
    func main() {
        var result universeTypeData
        jsonBytes := []byte(`{"data": [
                        {
                            "id": "recent_search",
                            "items": [],
                            "name": ""
                        },
                        {
                            "id": "popular_search",
                            "items": [],
                            "name": ""
                        },
                        {
                            "id": "digital",
                            "items": [],
                            "name": "DIGITAL"
                        }
                    ]}`)
        if err := json.Unmarshal(jsonBytes, &result); err != nil {
            fmt.Println(err)
        }
        fmt.Println(result)
    
    }
    
    func (universeData *universeTypeData) UnmarshalJSON(data []byte) error {
        var result Details
        if err := json.Unmarshal(data, &result); err != nil {
            return err
        }
        for _,value := range result.Data{
            switch value.ID {
                case "recent_search":
                    universeData.Recent = value
            }
        }
        return nil
    }
    

    Working code on Go Playground

    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止