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 ?

dspv70887
dspv70887 我同意gonutz,您可以编写自己的UnmarshallJSON版本,但要在其中混合逻辑,我的意思是1.从json解析和2.转换为所需的结构。更好的方法是使用辅助函数或更改json结构或使用额外的结构。问题是,如果您不熟悉该代码,则需要多长时间才能理解,修复和阅读代码/logic。
2 年多之前 回复
douwo8140
douwo8140 您已经知道答案:使用中介结构。对此可能没有严肃的论点。速度无关紧要,否则,您一开始就不会使用JSON。此结构加上转换的代码与编写您自己的UnmarshalJSON的大小和复杂度差不多。因此,只需将简单的方法与辅助结构一起使用,这将使最终阅读起来更加容易,这很重要。
2 年多之前 回复
douzou7012
douzou7012 您可以编写如何将json文件读取和解析为结构的信息...请查看此帖子:gregtrowbridge.com/golang-json-serialization-with-interfaces
2 年多之前 回复
doukongyong44772
doukongyong44772 你是什​​么意思?我对Go不太熟悉。
2 年多之前 回复
duanqiao1947
duanqiao1947 在主要结构上实现自己的UnmarshalJSON实现又如何呢?
2 年多之前 回复

1个回答

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
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问