douzhi9939 2017-10-21 22:07
浏览 89
已采纳

Golang自定义解组嵌套JSON

I have a JSON object that looks like this. It contains 3 meals a day for one week, for 21 total entries, since each meal is an individual entry.

{
    "name": "MealPlan 1508620645147",
    "items": [
        {
            "day": 1,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":869953,\"imageType\":\"jpg\",\"title\":\"Cream Cheese & Fruit Breakfast Pastries\"}"
        },
        {
            "day": 1,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":537176,\"imageType\":\"jpg\",\"title\":\"Leftover Rice Casserole\"}"
        },
        {
            "day": 1,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":595927,\"imageType\":\"jpg\",\"title\":\"Spinach and Cheddar Quiche\"}"
        },
        {
            "day": 2,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":536716,\"imageType\":\"jpg\",\"title\":\"Candied Pecan Waffles\"}"
        },
        {
            "day": 2,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":893265,\"imageType\":\"jpg\",\"title\":\"Tahini Date Smoothie Bowls\"}"
        },
        {
            "day": 2,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":512880,\"imageType\":\"jpg\",\"title\":\"Grilled Caprese Salad Sandwich for #SundaySupper\"}"
        },
        {
            "day": 3,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":648647,\"imageType\":\"jpg\",\"title\":\"Jumbo Blueberry Muffins\"}"
        },
        {
            "day": 3,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":548554,\"imageType\":\"jpg\",\"title\":\"Brie, Pesto, and Sweet Pepper Grilled Cheese\"}"
        },
        {
            "day": 3,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":438024,\"imageType\":\"jpg\",\"title\":\"Mother's Manicotti\"}"
        },
        {
            "day": 4,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":681594,\"imageType\":\"jpg\",\"title\":\"Huevos Rancheros\"}"
        },
        {
            "day": 4,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":99184,\"imageType\":\"jpg\",\"title\":\"Black Bean Tacos\"}"
        },
        {
            "day": 4,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":604514,\"imageType\":\"jpg\",\"title\":\"Cheddar Scallion Dutch Baby\"}"
        },
        {
            "day": 5,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":622672,\"imageType\":\"jpg\",\"title\":\"Cinnamon-Sugar Streusel Baked French Toast\"}"
        },
        {
            "day": 5,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":636178,\"imageType\":\"jpg\",\"title\":\"Broccoli Cheddar Soup, A Panera Bread Co. Copycat\"}"
        },
        {
            "day": 5,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":452482,\"imageType\":\"jpg\",\"title\":\"Slow Cooker Macaroni and Cheese I\"}"
        },
        {
            "day": 6,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":157272,\"imageType\":\"jpg\",\"title\":\"Pomegranate-Nutella Waffles\"}"
        },
        {
            "day": 6,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":619111,\"imageType\":\"jpg\",\"title\":\"Barley, Bulgur and Vegetable Vegan Casserole\"}"
        },
        {
            "day": 6,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":510089,\"imageType\":\"jpg\",\"title\":\"Stovetop Mac and Cheese\"}"
        },
        {
            "day": 7,
            "mealPlanId": 0,
            "slot": 1,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":551869,\"imageType\":\"jpg\",\"title\":\"Berry Smoothie\"}"
        },
        {
            "day": 7,
            "mealPlanId": 0,
            "slot": 2,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":590452,\"imageType\":\"jpg\",\"title\":\"Cheesy Baked Pasta with Eggplant and Artichokes\"}"
        },
        {
            "day": 7,
            "mealPlanId": 0,
            "slot": 3,
            "position": 0,
            "type": "RECIPE",
            "value": "{\"id\":590452,\"imageType\":\"jpg\",\"title\":\"Cheesy Baked Pasta with Eggplant and Artichokes\"}"
        }
    ]
}

I want to unmarshal it into an array of structs that will hold 3 meals each as Breakfast, Lunch, Dinner. So, I want my struct to look like this, where ID is the value.id field from the JSON, and Name is the value.title field from the JSON, Breakfast is the item with slot:1, Lunch is the item with slot:2 and Dinner is the item with slot:3.

type Day struct {
    Breakfast meal
    Lunch meal
    Dinner meal
}

type meal struct {
    ID   int
    Name string
}

How can I accomplish this in Go? My initial thought was to create an intermediate struct that holds all the data from the JSON, and then create another struct by using just the fields I need. How can I do this without using the intermediary struct ?

  • 写回答

1条回答 默认 最新

  • douqingnao9246 2017-10-23 22:52
    关注

    Did as mayo suggested and implemented UnmarshalJSON

    func (wp *WeekPlan) UnmarshalJSON(b []byte) error {
        wp.Days = make([]Day, 7)
        var f map[string]*json.RawMessage
        json.Unmarshal(b, &f)
    
        var v []map[string]interface{}
        json.Unmarshal(*f["items"], &v)
    
        for _, item := range v {
    
            day := int(item["day"].(float64)) - 1
            mealnumber := int(item["slot"].(float64))
    
            var value map[string]interface{}
            json.Unmarshal([]byte(item["value"].(string)), &value)
    
            fmt.Println(value)
    
            id := int(value["id"].(float64))
            name := value["title"].(string)
    
            thisMeal := Meal{ID: id, Name: name}
    
            var dateUpdate Day
    
            dateUpdate = wp.Days[day]
    
            switch mealnumber {
            case 1:
                dateUpdate.Breakfast = thisMeal
            case 2:
                dateUpdate.Lunch = thisMeal
            default:
                dateUpdate.Dinner = thisMeal
            }
    
            wp.Days[day] = dateUpdate
        }
    
        return nil
    }
    
    
    type WeekPlan struct {
        Days []Day
    }
    
    
    type Day struct {
        Breakfast Meal
        Lunch     Meal
        Dinner    Meal
    }
    
    
    type Meal struct {
        ID       int
        Name     string
        CookTime int
        Image    string
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题