我试图找出解组从 Neo4j 事务中获得的 JSON 结果的最佳方法。数据作为一组列和数据返回,我试图将它们硬塞到 Go 结构中。
这是我需要结果的结构:
type Person struct {
Id string `json:id`
Name string `json:name`
}
type Persons []*Person
这是我从交易中返回的 JSON:
{
"results":
[
{"columns":[],"data":[]},
{"columns":[],"data":[]},
{"columns":[],"data":[]},
{"columns":["r"],"data": // I only care this result which has data
[
{"row":[{"id":"1","name":"test1"}]}, // actual results
{"row":[{"id":"2","name":"test2"}]},
{"row":[{"id":"3","name":"test3"}]}
]
}
],
"errors":[]
}
这只是一个特殊的例子。其他事务将具有可变数量results(只有我关心的最后一个),并且需要将其解组到不同的结构中。我不想创建必须为每个模型结构创建一个唯一的结果结构。这是另一个例子:
这是一个不同的结构:
type Phone struct {
Id string `json:id`
Number string `json:number`
}
type Phones []*Phone
以及相应的 JSON:
{
"results":
[
{"columns":[],"data":[]},
{"columns":["r"],"data": // I only care this result which has data
[
{"row":[{"id":"4","number":"555-1234"}]}, // actual results
{"row":[{"id":"5","number":"555-1232"}]},
{"row":[{"id":"6","number":"555-1235"}]}
]
}
],
"errors":[]
}
目前我只是读出整个响应,使用字符串替换修复格式,然后正常解组,但我想知道是否有更好的方法。
这是我希望改进的当前实现。
// Structures to unmarshal Neo4j transaction results into.
type transactionResponse struct {
Results *json.RawMessage `json:"results"`
Errors []transactionError `json:"errors"`
}
// req is my POST to Neo4j
resp, err := db.client.Do(req)
defer resp.Body.Close()
if err != nil {
return fmt.Errorf("Error posting transaction: %s", err)
}
body, err := ioutil.ReadAll(resp.Body)
var txResponse transactionResponse
if err = json.Unmarshal(body, &txResponse); err == nil {
json.Unmarshal(formatTransactionResponse(*txResponse.Results), &Phones{});
}
相关分类