UnmarshalJSON导致堆栈溢出

时间:2016-01-18 16:24:41

标签: go

这有效:http://play.golang.org/p/-Kv3xAguDR

这会导致堆栈溢出:http://play.golang.org/p/1-AsHFj51O

我不明白为什么。在这种情况下使用JSONUnmarshaler接口的正确方法是什么?

package main

import (
    //"bytes"
    "encoding/json"
    "fmt"
    "strings"
)

type T interface {
    Printer()
}

type A struct{ JA string }

func (t A) Printer() { fmt.Print("A") }

/*
func (t *A) UnmarshalJSON(data []byte) error {
    i := A{}
    dec := json.NewDecoder(bytes.NewReader(data))
    if err := dec.Decode(&i); err != nil {
        return err
    }
    i.Printer()
    *t = i
    return nil
}
*/

var vI []T

func main() {
    vI = []T{&A{}}
    get()
}

func get() {
    dec := json.NewDecoder(strings.NewReader("[{\"JA\":\"OK\"}]"))
    if err := dec.Decode(&vI); err != nil {
        fmt.Print(err)
    }
    for _, v := range vI {
        v.Printer()
    }
}

1 个答案:

答案 0 :(得分:1)

dec.Decode(&i)

会致电您的UnmarshalJSON,而Decode会拨打// Type a has no UnmarshalJSON. type a A i := a{} dec := json.NewDecoder(bytes.NewReader(data)) if err := dec.Decode(&i); err != nil { return err } // Convert back to A. tt := A(i) tt.Printer() *t = tt // ... ,依此类推。如果你需要解组你的JSON然后用它做一些事情,一个简洁的技术就是声明一个本地类型,将数据解组到它中,然后转换回你想要的类型:

a

游乐场:http://play.golang.org/p/HWamV3MbvW

类型A没有方法(因此没有堆栈溢出),但是convertibleprivate final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //aVariable = 0; // Do what you want here mContext.unregisterReceiver(this); if(intent.getAction().equals(NOTIFICATION_DELETED_ACTION)) { mNotififDismissId = intent.getExtras().getInt("IdDismiss"); if(mNotififDismissId == globalTweetNotif) cancelAll(context); else cancelNotification(context, mNotififDismissId); } } };

相关问题