我无法使用golang通过服务器响应解析此json:
{
"id": 1,
"description": "{\"uDes\":\"\",\"reDes\":[{\"des\":\"aaa,,request=<?xml version=“1.0“ encoding=“GBK“?><Req ver=“3.0“><HR version=“3.0“ cd=“0“><src><\\\\/src><license><\\\\/license><clientid>com.sample.xo<\\\\/clientid><ii>8603<\\\\/ii><im>46002910<\\\\/im><uuid>da032b2<\\\\/uuid><reqid>-21851<\\\\/reqid><smc>44:91<\\\\/smc><sdv>2.0.201501131131.a.r<\\\\/sdv><corv>V1.1.0r<\\\\/corv><\\\\/HDR><DRR nettype=“LTE“ inftype=“1“><mc>460<\\\\/cc><mnc>00<\\\\/mnc><lac>34809<\\\\/lac><cellid>8842241<\\\\/cellid><signal>-69<\\\\/signal><\\\\/DRR><\\\\/Cell_Req>&retype=3×tamp=1469550331136\"}]}"
}
请注意关键&#39;说明&#39;有很多非法的字符。我只想把它作为字符串存储到我们的数据库中。 go代码片段如下:
import (
"fmt"
"net/http"
"encoding/json"
)
var p := fmt.Println
type DataSlice struct{
Id int
Destription string
}
func main() {
p("Start fetching data..")
resp,err := http.Get("http://127.0.0.1/pis")
if err != nil{
//handle error
p(err)
}else{
defer resp.Body.Close()
var jsonInst DataSlice
p("Start decode json body..")
err := json.NewDecoder(resp.Body).Decode(&jsonInst)
if err != nil {
panic(err)
}else{
//do insert here
}
}
}
此代码执行正常,但描述值为空。请帮我解决此问题。非常感谢!
答案 0 :(得分:1)
请注意,您的Destription
结构中有一个拼写错误 - Description
而不是DataSlice
。请参阅PlayGround中的以下示例,该示例成功解析了您的JSON blob - https://play.golang.org/p/CeoCH2SJXh:
package main
import (
"encoding/json"
"fmt"
"strings"
)
var input = `{
"id": 1,
"description": "{\"uDes\":\"\",\"reDes\":[{\"des\":\"aaa,,request=<?xml version=“1.0“ encoding=“GBK“?><Req ver=“3.0“><HR version=“3.0“ cd=“0“><src><\\\\/src><license><\\\\/license><clientid>com.sample.xo<\\\\/clientid><ii>8603<\\\\/ii><im>46002910<\\\\/im><uuid>da032b2<\\\\/uuid><reqid>-21851<\\\\/reqid><smc>44:91<\\\\/smc><sdv>2.0.201501131131.a.r<\\\\/sdv><corv>V1.1.0r<\\\\/corv><\\\\/HDR><DRR nettype=“LTE“ inftype=“1“><mc>460<\\\\/cc><mnc>00<\\\\/mnc><lac>34809<\\\\/lac><cellid>8842241<\\\\/cellid><signal>-69<\\\\/signal><\\\\/DRR><\\\\/Cell_Req>&retype=3×tamp=1469550331136\"}]}"
}`
var p = fmt.Println
type DataSlice struct {
Id int
Description string
}
func main() {
var inst DataSlice
p("Start decode json body..")
err := json.NewDecoder(strings.NewReader(input)).Decode(&inst)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", inst)
}
输出:
Start decode json body..
main.DataSlice{Id:1, Description:"{\"uDes\":\"\",\"reDes\":[{\"des\":\"aaa,,request=<?xml version=“1.0“ encoding=“GBK“?><Req ver=“3.0“><HR version=“3.0“ cd=“0“><src><\\\\/src><license><\\\\/license><clientid>com.sample.xo<\\\\/clientid><ii>8603<\\\\/ii><im>46002910<\\\\/im><uuid>da032b2<\\\\/uuid><reqid>-21851<\\\\/reqid><smc>44:91<\\\\/smc><sdv>2.0.201501131131.a.r<\\\\/sdv><corv>V1.1.0r<\\\\/corv><\\\\/HDR><DRR nettype=“LTE“ inftype=“1“><mc>460<\\\\/cc><mnc>00<\\\\/mnc><lac>34809<\\\\/lac><cellid>8842241<\\\\/cellid><signal>-69<\\\\/signal><\\\\/DRR><\\\\/Cell_Req>&retype=3×tamp=1469550331136\"}]}"}