构建一个具有数组值的JSON对象。

huangapple go评论110阅读模式
英文:

Building a JSON object with an array as a value

问题

我需要在一个 JSON 对象中发送一个包含以下结构的数组:

{"extent":[-76.0624694824, 36.8856620774, -75.9800720215,36.9449529607]}

我该如何做呢?我不能使用典型的方式:

var jsonprep string = `{"extent":` + []float32{-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607} + `}`
var jsonStr = []byte(jsonprep)

因为类型不匹配。我正在尝试将其发送到一个期望它是一个数组的服务器,但我得到了以下错误:

请求内容格式错误:
预期的是一个 JsArray,但得到了 "[-76.0624694824, 36.8856620774, -75.9800720215,36.9449529607]"
英文:

I need to send an Array inside a JSON object with the structure:

{"extent":[-76.0624694824, 36.8856620774, -75.9800720215,36.9449529607]}

How would I do this? I can't use the typical:

var jsonprep string = `{"extent":` + []float32{-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607} + `}`
var jsonStr = []byte(jsonprep)

because of the type mismatch. I am trying to send this to a server that expects it to be an array as I get the error,

The request content was malformed:
Expected List as JsArray, but got "[-76.0624694824, 36.8856620774, -75.9800720215,36.9449529607]"

答案1

得分: 2

如果你期望数组在某个时刻发生变化,可以考虑使用encoding/json包。

然后你可以创建一个JSON对象的结构原型,然后使用json.Marshal()将其序列化为JSON对象的[]byte表示形式,以便进行传输(无论是通过stdio、tcp还是其他方式)。

例如:

type ExampleJSON struct {
    Extent []float32 `json:"extent"`
}

func main(){
    ex := &ExampleJSON{
        Extent: []float32{-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607},
    }
    jsonBytes, err := json.Marshal(ex)
    if err != nil {
        //...
    }
}
英文:

If you are expecting that the array will change at some point, consider using the encoding/json package

Then you can create a struct prototype of your JSON object, then use json.Marshal() to serialize it into a []byte representation of the JSON object for transfer (whether by stdio, tcp, whatever).

e.g.

type ExampleJSON struct {
    Extent []float32 `json:"extent"`
}

func main(){
    var ex := &ExampleJSON{
        []float32{-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607}
    }
    jsonBytes, err := json.Marshal(ex)
    if err != nil {
        //...
    }
}

答案2

得分: -1

我过于思考了。答案是:

var jsonprep string = `{"extent":[-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607]}`
英文:

I was overthinking it. The answer was:

var jsonprep string = `{"extent":[-76.0624694824, 36.8856620774, -75.9800720215, 36.9449529607]}`

huangapple
  • 本文由 发表于 2016年3月17日 23:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/36064958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定