波斯汪
您需要将指针传递给Decode和Unmarshal。我用和建立了一个可运行的样本,两者都返回。您可以通过使用或包装您的预期内容来将请求正文与您的静态预期内容进行比较(就像您在问题中尝试做的那样)。这是代码:func JSONEqual(a, b io.Reader)JSONBytesEqual(a, b []byte)(bool, error)bytes.NewBufferstrings.NewReaderpackage mainimport ( "encoding/json" "fmt" "io" "reflect")// JSONEqual compares the JSON from two Readers.func JSONEqual(a, b io.Reader) (bool, error) { var j, j2 interface{} d := json.NewDecoder(a) if err := d.Decode(&j); err != nil { return false, err } d = json.NewDecoder(b) if err := d.Decode(&j2); err != nil { return false, err } return reflect.DeepEqual(j2, j), nil}// JSONBytesEqual compares the JSON in two byte slices.func JSONBytesEqual(a, b []byte) (bool, error) { var j, j2 interface{} if err := json.Unmarshal(a, &j); err != nil { return false, err } if err := json.Unmarshal(b, &j2); err != nil { return false, err } return reflect.DeepEqual(j2, j), nil}func main() { a := []byte(`{"x": ["y",42]}`) b := []byte(`{"x": ["y", 42]}`) c := []byte(`{"z": ["y", "42"]}`) empty := []byte{} bad := []byte(`{this? this is a test.}`) eq, err := JSONBytesEqual(a, b) fmt.Println("a=b\t", eq, "with error", err) eq, err = JSONBytesEqual(a, c) fmt.Println("a=c\t", eq, "with error", err) eq, err = JSONBytesEqual(a, empty) fmt.Println("a=empty\t", eq, "with error", err) eq, err = JSONBytesEqual(a, bad) fmt.Println("a=bad\t", eq, "with error", err)}它输出:a=b true with error <nil>a=c false with error <nil>a=empty false with error EOFa=bad false with error invalid character 't' looking for beginning of object key string