tôi sử dụng một yêu cầu HTTP Golang để có được sản lượng json như sau. Các dịch vụ web tôi đang cố gắng truy cập Micrsoft Translator https://msdn.microsoft.com/en-us/library/dn876735.aspxGot lỗi "nhân vật không hợp lệ 'i' tìm kiếm đầu giá trị” từ json.Unmarshal
//Data struct of TransformTextResponse
type TransformTextResponse struct {
ErrorCondition int `json:"ec"` // A positive number representing an error condition
ErrorDescriptive string `json:"em"` // A descriptive error message
Sentence string `json:"sentence"` // transformed text
}
//some code ....
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return "", tracerr.Wrap(err)
}
transTransform = TransformTextResponse{}
err = json.Unmarshal(body, &transTransform)
if err != nil {
return "", tracerr.Wrap(err)
}
tôi đã nhận một lỗi từ invalid character 'ï' looking for beginning of value
vì vậy, tôi cố gắng in body
như chuỗi fmt.Println(string(body))
, nó hiển thị:
{"ec":0,"em":"OK","sentence":"This is too strange i just want to go home soon"}
Có vẻ như các dữ liệu không có bất kỳ vấn đề, vì vậy tôi đã cố gắng để tạo ra các giá trị như nhau bởi jason.Marshal
transTransform := TransformTextResponse{}
transTransform.ErrorCondition = 0
transTransform.ErrorDescriptive = "OK"
transTransform.Sentence = "This is too strange i just want to go home soon"
jbody, _ := json.Marshal(transTransform)
tôi tìm thấy dữ liệu gốc có thể có vấn đề, vì vậy tôi cố gắng để so sánh hai dữ liệu ở định dạng []byte
.
Dữ liệu từ response.Body
:
[239 187 191 123 34 101 99 34 58 48 44 34 101 109 34 58 34 79 75 34 44 34 115 101 110 116 101 110 99 101 34 58 34 84 104 105 115 32 105 115 32 116 111 111 32 115 116 114 97 110 103 101 32 105 32 106 117 115 116 32 119 97 110 116 32 116 111 32 103 111 32 104 111 109 101 32 115 111 111 110 34 125]
Dữ liệu từ json.Marshal
[123 34 101 99 34 58 48 44 34 101 109 34 58 34 79 75 34 44 34 115 101 110 116 101 110 99 101 34 58 34 84 104 105 115 32 105 115 32 116 111 111 32 115 116 114 97 110 103 101 32 105 32 106 117 115 116 32 119 97 110 116 32 116 111 32 103 111 32 104 111 109 101 32 115 111 111 110 34 125]
Bất kỳ ý tưởng làm thế nào tôi phân tích response.Body
này và unmarshal nó vào cấu trúc dữ liệu?
Ba byte đầu tiên là [BOM] (https://en.wikipedia.org/wiki/Byte_order_mark) (239 187 191) cho UTF-8. Có máy chủ * không * bao gồm UTF-8 BOM hoặc tung ra 3 byte đầu tiên trước khi xử lý phần còn lại (là chuỗi được mã hóa UTF-8 thực tế). – user2864740