2016-07-27 214 views
1

我有這樣的JSON:跳過解碼Unicode字符串進行解:golang

{ 
    "code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d" 
} 

而且這個結構

type Text struct { 
    Code string 
} 

如果我使用任何json.UnmarshalNewDecoder.Decode的,Unicode的轉化爲實際的中文。所以Text.Code

在豐德爾Berro舒適的1房單位

我不希望它來轉換,我想同樣的unicode字符串。

+0

你還需要讓unicode字符在沒有在JSON文件中轉義時被轉義嗎?例如。如果JSON文件看起來像這樣:'{「code」:「在豐德爾Berro舒適的1房單位」}' – roeland

回答

4

您可以自定義解碼器https://play.golang.org/p/H-gagzJGPI

package main 

import (
    "encoding/json" 
    "fmt" 
) 

type RawUnicodeString string 

func (this *RawUnicodeString) UnmarshalJSON(b []byte) error { 
    *this = RawUnicodeString(b) 
    return nil 
} 

func (this RawUnicodeString) MarshalJSON() ([]byte, error) { 
    return []byte(this), nil 
} 

type Message struct { 
    Code RawUnicodeString 
} 

func main() { 
    var r Message 
    data := `{"code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"}` 
    json.Unmarshal([]byte(data), &r) 
    fmt.Println(r.Code) 
    out, _ := json.Marshal(r) 
    fmt.Println(string(out)) 
} 
+0

感謝您的回覆,我們在PHP中有一些服務需要使用相同的數據,我已經實現了適用於我的自定義MarshalJSON。謝謝。 –

+0

剛剛在這發現了一個小問題,它在字符串中加了''''雙引號。當你打印'r.Code'時,你可以用'「」'看到字符串。我試着修剪'UnmarshalJSON'內的數組的第一個和最後一個字節,它工作。但我不確定這是否是正確的解決方案。 –

+0

@RanveerSingh你可以嘗試使用un unmarshaller'RawUnicodeString(b [1:len(b)-1])'應該可以。 –

0

你可以使用json.RawMessage,而不是字符串做到這一點。 https://play.golang.org/p/YcY2KrkaIb

package main 

    import (
     "encoding/json" 
     "fmt" 
    ) 

    type Text struct { 
     Code json.RawMessage 
    } 

    func main() { 
     data := []byte(`{"code":"\u5728\u4e30\u5fb7\u5c14Berro\u8212\u9002\u76841\u623f\u5355\u4f4d"}`) 
     var message Text 
     json.Unmarshal(data, &message) 
     fmt.Println(string(message.Code)) 
    } 
+0

對不起,提示編輯錯誤的帖子:-( –