douhuireng4407 2014-10-25 21:06
浏览 62
已采纳

如何将未编组的Golang对象转换为指定变量的类型

I'd like to marshal a variety of objects to file, then unmarshal them, and convert them back to their original type by getting the type of the variables which were marshalled. The key point is that I'd like to convert the unmarshalled object to the type of a specified variable, without specifying the type.

The short pseudocode:

// Marshal this
item := Book{"The Myth of Sisyphus", "Albert Camus"}
// Then unmarshal and convert to the type of the item variable.
itemType := reflect.TypeOf(item)
newItem itemType = unmarshalledItem.(itemType)  // This is the problem.
fmt.Println("Unmarshalled is:", reflect.TypeOf(newItem)) // Should print *main.Book

The full code:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
    "reflect"
)

type Book struct {
    Title  string
    Author string
}

func main() {
    // Create objects to marshal.
    book := Book{"The Myth of Sisyphus", "Albert Camus"}
    box := make(map[string]interface{})
    box["The Myth of Sisyphus"] = &book
    itemType := reflect.TypeOf(box["The Myth of Sisyphus"])
    fmt.Println("Book is:", itemType)

    // Marshal objects to file.
    err := Write(&book)
    if err != nil {
        fmt.Println("Unable to save store.", err)
        return
    }

    // Unmarshal objects from file.
    untyped := make(map[string]interface{})
    bytes, err := ioutil.ReadFile("store.txt")
    if err != nil {
        fmt.Println("Unable to load store.", err)
        return
    }
    err = json.Unmarshal(bytes, &untyped)
    if err != nil {
        fmt.Println("Err in store unmarshal.", err)
        return
    }

    // Get Title property of unmarshalled object,
    // and use that to get variable type from box map.
    for k, v := range untyped {
        if k == "Title" {
            itemTitle := v.(string)
            fmt.Println("Cast item having title:", itemTitle)
            targetType := reflect.TypeOf(box[itemTitle])
            fmt.Println("Type to cast to is:", targetType)
            // Convert untyped to targetType.
            // This is the problem.
            typed targetType = untyped.(targetType)
            fmt.Println("Unmarshalled is:", reflect.TypeOf(typed)) // Should print *main.Book
        }
    }
}

func Write(b *Book) error {
    data, err := json.Marshal(b)
    if err != nil {
        return err
    }
    newFilename := "store.txt"
    f, err := os.OpenFile(newFilename, os.O_CREATE|os.O_TRUNC, 0660)
    if err != nil {
        return err
    }
    _, err = f.WriteString(string(data) + "
")
    if err != nil {
        return err
    }
    return nil
}
  • 写回答

1条回答 默认 最新

  • duanfu2562 2014-10-26 05:11
    关注

    This might work in a dynamically typed language, but it wont work here because Go is statically typed.

    The book is not stored as a Book, its stored as a json string and the json unmarshaller has no idea that its a Book unless you tell it so. i.e. it doesn't know to map the fields to a Book object.

    You can't cast the unmarshalled 'untyped' into a Book because it is not a Book it is a map[string]interface{} which happens to look exactly like a Book.

    What you would need to do is

    1. unmarshal the json into a map[string]interface{} then read the title.
    2. use an if statement or a switch statement based on the type
    3. unmarshal the json again into an object of that type (e.g. a Book)

    Something like this I guess:

    // check the type
    if targetType.String() == "*main.Book" {
        // unmarshall it again as a Book
        var typedBook Book
        _ = json.Unmarshal(bytes, &typedBook)
        fmt.Println("Unmarshalled is:", reflect.TypeOf(typedBook)) // Should print *main.Book
    } else if targetType.String() == "*main.Magazine" {
        // unmarshal a magazine or whatever
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题