Comments (8)
Context.JSON
accepts an interface{}
which means that you can pass any value.
res := []string{"foo", "bar"}
c.JSON(200, res)
Has the expected result:
["foo","bar"]
from gin.
For context.JSON supporting slice of nested structs
type Tag struct {
Name string `json:"name" form:"name" binding:"required"`
Description string `json:"description" form:"description" binding:"required"`
ExtraData TagExtra `json:"extra"`
}
tags := getTags() // which return []Tag
c.JSON(200, tags)
in result ExtraData looks empty even though ExtraData exist
[
{
"name": "question",
"description": "question is something cool",
"extra": {}
},
{
"name": "intro",
"description": "intro is something cool",
"extra": {}
},
...
]
when assigning to an interface slice everything seems to work out.
type Tag struct {
Name string `json:"name" form:"name" binding:"required"`
Description string `json:"description" form:"description" binding:"required"`
ExtraData TagExtra `json:"extra"`
}
tags := getTags() // which return []Tag
var interfaceSlice []interface{} = make([]interface{}, len(tags))
for i, tag := range tags {
interfaceSlice[i] = tag
}
c.JSON(200, interfaceSlice)
[
{
"name": "question",
"description": "question is something cool",
"extra":
{
"id": 1,
"created_at": "2015-08-25T00:35:55.408537Z"
...
},
...
]
For now i'm reassigning to interfaceslice. Is there a better way to do this?
from gin.
byteSlice,err := json.Marshal(yourSlice)
if err != nil {
panic(err)
}
c.Writer.Header().Set("Content-Type","application/json")
c.Writer.WriteHeader(200)
c.Writer.Write(byteSlice)
this doesn't work.
You say, "nested arrays"..
I meant "slice of nested structs" sorry for that misunderstanding. Edited the comment
from gin.
@alexandernyquist is right.
Check this out: http://golang.org/pkg/encoding/json/
Context.JSON
uses it
from gin.
type Tag struct {
Name string `json:"name" form:"name" binding:"required"`
Description string `json:"description" form:"description" binding:"required"`
ExtraData TagExtra `json:"extra"`
}
type TagExtra struct {
TypeInformation TypeInformation `json:"type_information"`
SenderUser User `json:"sender_user"`
}
and getTags returns []Tag
. The inner struct (TagExtra) screws encoding/json somehow.
tags := getTags()
var interfaceSlice []interface{} = make([]interface{}, len(tags))
for i, tag := range tags {
interfaceSlice[i] = tag
}
c.JSON(200, tags[0]) // returns TagExtra's information correctly
c.JSON(200, tags) // returns TagExtra's information empty
c.JSON(200, interfaceSlice) // returns TagExtra's information correctly
So expected result will be something like
[
{
"name": "question",
"description": "question is something cool",
"extra":
{
"type_information":
{
...
},
"sender_user":
{
...
}
}
},
...
]
but instead it returns
[
{
"name": "question",
"description": "question is something cool",
"extra": {}
},
...
]
I hope I was able to clarify. Thank you.
from gin.
@thellimist
Try taking your []Tag slice and converting it to a []byte slice and write
it manually like this (you need to import "encoding/json"):
byteSlice,err := json.Marshal(yourSlice)
if err != nil {
panic(err)
}
c.Writer.Header().Set("Content-Type","application/json")
c.Writer.WriteHeader(200)
c.Writer.Write(byteSlice)
Can you see ExtraData in the json output if you do it this way? Do you get
an error at all? Maybe this can give you some more insight as to how your
Struct is being misinterpreted by gins c.JSON function.
You say, "nested arrays", but it looks like ExtraData is just a dictionary, make sure you are using a slice to hold the data that is inside ExtraData (eg. []TagExtra) if you want an array.
Lastly, you don't want to display ExtraData if its empty, but you are sacrificing your output fieldname to do so. The "encoding/json" package allows you to double up with the omitempty option like so: json:"myName,omitempty"
On Mon, Aug 24, 2015 at 3:26 PM, Furkan Yilmaz [email protected]
wrote:
type Tag struct {
Name stringjson:"name" form:"name" binding:"required"
Description stringjson:"description" form:"description" binding:"required"
ExtraData TagExtrajson:"extra"
}tags := getTags() // which return []Tag
c.JSON(200, tags)
results is although ExtraData exist
[
{
"name": "question",
"description": "question is something cool",
"ExtraData": {}
},
{
"name": "intro",
"description": "intro is something cool",
"ExtraData": {}
},
...
]when assigning to an interface slice everything seems to work out.
type Tag struct {
Name stringjson:"name" form:"name" binding:"required"
Description stringjson:"description" form:"description" binding:"required"
ExtraData TagExtrajson:"extra"
}tags := getTags() // which return []Tag
var interfaceSlice []interface{} = make([]interface{}, len(tags))
for i, tag := range tags {
interfaceSlice[i] = tag
}c.JSON(200, interfaceSlice)
[
{
"name": "question",
"description": "question is something cool",
"ExtraData":
{
"id": 1,
"created_at": "2015-08-25T00:35:55.408537Z"
...
},
...
]—
Reply to this email directly or view it on GitHub
#87 (comment).
from gin.
@thellimist could you post the code for your getTags() function? I'm trying to figure out where in your Extra struct the non interface type screws with encoding/json.
When you said array I knew you meant slice, I just wanted to make sure you were storing a slice []ExtraData and not just ExtraData in your top level struct.
from gin.
byteSlice,err := json.Marshal(yourSlice) if err != nil { panic(err) } c.Writer.Header().Set("Content-Type","application/json") c.Writer.WriteHeader(200) c.Writer.Write(byteSlice)
this doesn't work.
You say, "nested arrays"..
I meant "slice of nested structs" sorry for that misunderstanding. Edited the comment
I also want to know how to response that string as json.
from gin.
Related Issues (20)
- Will it be made into a more comprehensive framework later on? HOT 4
- How does the gin close the log file? HOT 3
- Should we use url.PathUnescape instead of url.QueryUnescape when UnescapePathValues is true
- go get failed: The requested name is valid, but no data of the requested type was found HOT 1
- Attach Response Headers (or middlewares) to redirected requests (CORS issues) HOT 1
- Should context.GetRawData() also copy body to BodyBytesKey? HOT 3
- YAML BindBody should not parse JSON content HOT 1
- Gin do not support javascript ? HOT 5
- Does gin.Recovery() run before or after Group middleware? HOT 1
- How can i prevent a http connection to close HOT 3
- BasicAuth is not suitable for proxy auth
- Can't get status as expected from context.Status() HOT 1
- Gin Context implementation breaks context.Context contract HOT 4
- [Suggestions] Introducing an AI-powered robot to assist with daily issue and pull request (PR) tasks.
- Need c.JSON() response like behaviour for c.SSEvent() response for supporting first party clients like OpenAI SDK HOT 2
- custom time.Time type can not use bindQuery get a value. HOT 3
- configure server parameters HOT 1
- The binding:"required" tag does not seem to work for struct types HOT 3
- Is there a way to preserve order in JSON on response? HOT 1
- redirect is not success HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from gin.