Cannot decode json data

I am creating an ajax call to server and post data in json file. But at server side, it can only read the first element of object (FeatureID) but the second (BMPCode) is 0. thanks for any help.

Client:

$("#button").click(function(event) {
            /* Act on the event */
            var featureArray = [];
            var a = new Object();
            a.featureID = 2;
        a.bmpCode = 7;
        var b = new Object();
        b.featureID = 2;
        b.bmpCode = 7;
        featureArray.push(a);
        featureArray.push(b);
        var jsonArray = JSON.stringify(featureArray);
        $.ajax({
            url: '/ajax2',
            type: "post",
            contentType: 'application/json; charset=utf-8',
            data: jsonArray,
            dataType: 'json',
            success: function(r) {
                $('#response').append(r[0].FeatureID);
            }
        });
    });

Server:

type BMPInfo struct {
    FeatureID int
    BMPInfo   int
   }
func ajaxHandler2(w http.ResponseWriter, r *http.Request) {
    var d []BMPInfo
    err := json.NewDecoder(r.Body).Decode(&d)
    if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
}
    fmt.Println(d[0].FeatureID)
    fmt.Println(d[0].BMPInfo)
    a, err := json.Marshal(d)
    if err != nil {
	    http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    w.Write(a)
}

I know the reason. because decode requires an insensitive matach between the json and the element name of struct…

Shouldn’t it be:

type BMPInfo struct {
    FeatureID int `json:"featureId"`
    BMPCode   int `json:"bmpCode"` // bmpCode instead of bmpInfo
}

?

Here’s an working example:

https://play.golang.org/p/6PES7Nl6au

yeah, thanks so much. I do not know why I make this type of mistakes all the time. :cry:

Haha, yeah, I know how that feels :laughing:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.