2016-07-27 218 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

对不起,提示编辑错误的帖子:-( –