How to create custom key in json response using golang

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

How to create custom key in json response using golang

问题

我通过golang获得了以下的JSON响应。

[
    {
        "CreatedOn": "03-22-2015",
        "JSONReceived": [
            {
                "EzpOrderID": "ezp_126",
                "FirstName": "Kumar",
                "LastName": "S",
                "OrderDesc": "Sample"
            }
        ],
        "Status": "0",
        "id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
    },
    {
        "CreatedOn": "03-22-2015",
        "JSONReceived": [
            {
                "EzpOrderID": "ezp_126",
                "FirstName": "Vasanth",
                "LastName": "K",
                "OrderDesc": "Sample"
            }
        ],
        "Status": "0",
        "id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
    }
]

但是我需要按照指定的键创建响应,示例响应如下。请问如何使用golang编程实现?

{
    "returnResponseData": [
        {
            "CreatedOn": "03-22-2015",
            "JSONReceived": [
                {
                    "EzpOrderID": "ezp_126",
                    "FirstName": "Kumar",
                    "LastName": "S",
                    "OrderDesc": "Sample"
                }
            ],
            "Status": "0",
            "id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
        },
        {
            "CreatedOn": "03-22-2015",
            "JSONReceived": [
                {
                    "EzpOrderID": "ezp_126",
                    "FirstName": "Vasanth",
                    "LastName": "K",
                    "OrderDesc": "Sample"
                }
            ],
            "Status": "0",
            "id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
        }
    ]
}

请帮助我使用golang实现这个任务。

以下是完整的源代码:

func orderList(w http.ResponseWriter, request *http.Request) {

    rows, err := r.Table("orders").Run(session)
    if err != nil {
        fmt.Println(err)
        return
    }
     
    var resultSet []interface{}
    
    err = rows.All(&resultSet)
    if err != nil {
        fmt.Printf("Error scanning database result: %s", err)
        return
    }

    if origin := request.Header.Get("Origin"); origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        w.Header().Set("Access-Control-Allow-Methods", "GET")
        w.Header().Set("Access-Control-Allow-Headers",
        "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(200)            
    json.NewEncoder(w).Encode(map[string]interface{}{"returnResponseData": resultSet})
}
英文:

I get a following json response through golang.

 [
    {
        "CreatedOn": "03-22-2015",
        "JSONReceived": [
            {
                "EzpOrderID": "ezp_126",
                "FirstName": "Kumar",
                "LastName": "S",
                "OrderDesc": "Sample"
            }
        ],
        "Status": "0",
        "id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
    },
    {
        "CreatedOn": "03-22-2015",
        "JSONReceived": [
            {
                "EzpOrderID": "ezp_126",
                "FirstName": "Vasanth",
                "LastName": "K",
                "OrderDesc": "Sample"
            }
        ],
        "Status": "0",
        "id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
    }
]..

But i need to create with key in response. sample response as follows. How to achieve using golang programming.

 {
	"returnResponseData": [{
		"CreatedOn": "03-22-2015",
		"JSONReceived": [{
			"EzpOrderID": "ezp_126",
			"FirstName": "Kumar",
			"LastName": "S",
			"OrderDesc": "Sample"
		}],
		"Status": "0",
		"id": "80acbdad-8aae-4d6c-ac63-2a02a9db64b4"
	}, {
		"CreatedOn": "03-22-2015",
		"JSONReceived": [{
			"EzpOrderID": "ezp_126",
			"FirstName": "Vasanth",
			"LastName": "K",
			"OrderDesc": "Sample"
		}],
		"Status": "0",
		"id": "8f7f52a5-793a-45bd-a9b7-ed41495e0ee3"
	}]
}

Please help me to achieve this task using golang.

Whole Source code as follows:

 func orderList(w http.ResponseWriter, request *http.Request) {

    rows, err := r.Table("orders").Run(session)
    if err != nil {
        fmt.Println(err)
        return
    }
	     
	var resultSet []interface{}
	
	err = rows.All(&resultSet)
	if err != nil {
		fmt.Printf("Error scanning database result: %s", err)
		return
	}

	if origin := request.Header.Get("Origin"); origin != "" {
		w.Header().Set("Access-Control-Allow-Origin", origin)
		w.Header().Set("Access-Control-Allow-Methods", "GET")
		w.Header().Set("Access-Control-Allow-Headers",
		"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
	}
	
	
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)            
	json.NewEncoder(w).Encode(resultSet)
	
	
	
}

答案1

得分: 3

你需要像这样定义另一种类型:

type Wrapper struct {
    ReturnResponseData []interface{} `json:"returnResponseData"`
}

然后编码包含你的响应集的包装器:

json.NewEncoder(w).Encode(&Wrapper{ReturnResponseData: resultSet})

请注意,你需要使用属性标签来实现名称为"returnResponseData",并以小写字母开头(因为编码器默认不会编码私有属性)。

英文:

You have to define another type like this:

type Wrapper struct {
    ReturnResponseData []interface{} `json:"returnResponseData"`
}

and then encode wrapper, containing your response set:

json.NewEncoder(w).Encode(&Wrapper{ReturnResponseData: resultSet})

Notice, that you have to use property tag to achieve the name "returnResponseData", starting of a small letter (because encoder doesn't encode private properties by default).

huangapple
  • 本文由 发表于 2016年3月31日 14:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/36326033.html
匿名

发表评论

匿名网友

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

确定