Skip to content

In standard routing, when the input parameter is JSON Array, json.RawMessage cannot be used #3449

Closed
@shuqingzai

Description

@shuqingzai

What version of Go and system type/arch are you using?

#-> % go version
go version go1.21.7 darwin/amd64

What version of GoFrame are you using?

#-> % gf version
v2.6.4
Welcome to GoFrame!
Env Detail:
  Go Version: go1.21.7 darwin/amd64
  GF Version(go.mod):
    github.com/gogf/gf/v2@v2.6.4
CLI Detail:
  Installed At: /Code/go/bin/gf
  Built Go Version: go1.21.7
  Built GF Version: v2.6.4
Others Detail:
  Docs: https://goframe.org
  Now : 2024-03-11T13:36:04+08:00

Can this bug be re-produced with the latest release?

What did you do?

示例代码

package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type HelloReq struct {
	g.Meta `path:"/hello" method:"POST" sm:"hello" tags:"示例"`

	Name    string          `json:"name" v:"required" dc:"名称"`
	JSONRaw json.RawMessage `json:"jsonRaw" dc:"原始JSON"`
}
type HelloRes struct {
	Name    string          `json:"name" v:"required" dc:"名称"`
	JSONRaw json.RawMessage `json:"jsonRaw" dc:"原始JSON"`
}

type Hello struct {
}

func (Hello) Say(_ context.Context, req *HelloReq) (res *HelloRes, err error) {
	fmt.Printf("req.Name: %s\n", req.Name)
	fmt.Printf("req.JSONRaw: %s\n", string(req.JSONRaw))
	res = &HelloRes{
		Name:    req.Name,
		JSONRaw: req.JSONRaw,
	}
	return
}

func main() {
	s := g.Server()
	s.Use(ghttp.MiddlewareHandlerResponse)
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.Bind(
			new(Hello),
		)
	})
	s.Run()
}

请求示例

  1. JSON 使用 Object ,这是可以的
curl --location --request POST 'http://127.0.0.1:8199/hello' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--data-raw '{
  "name": "string",
  "jsonRaw": {
        "jkey": "value1",
        "jkey2": 2
    }
}'
  1. JSON 使用 Array ,无法序列化
curl --location --request POST 'http://127.0.0.1:8199/hello' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--data-raw '{
  "name": "string",
  "jsonRaw": [
    {
        "jkey": "value1",
        "jkey2": 2
    },
    {
        "jkey": "value12",
        "jkey2": 22
    }
  ]
}'

由于 Array 无法序列化,导致我直接输出原参数会报错

WriteJson failed: json.Marshal failed: json: error calling MarshalJSON for type json.RawMessage: invalid character '\x00' looking for beginning of value

参考:

case "RawMessage", "json.RawMessage":

其中使用 Bytes 转换,导致无法获取源数据,参考:

for i := range bytes {

What did you expect to see?

What did you see instead?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIt is confirmed a bug, but don't worry, we'll handle it.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions