user7637864
user7637864

Reputation: 237

Get JSON Key values using GSON library

I am trying to get the JSON Object from my form.

Please find the JSON Below:

[{"id":["4"]},{"Flap":["NA"]}]

So I am using a hidden attribute to save the value into a JsonObject (from Gson library) in my ModelForm. When I call this object from my controller, I am not able to get the values by key.

In jsp:

<form:form modelAttribute="myForm" action="/action">
<input type="hidden" name="jsonObject" id="jsonObj" value=""/>
<input type="submit" value="Submit" onclick="function getjson()"/>
</form:form>

In js I am collecting all checked boxes and saving the information in the form of Json on submitting the value.

In JS:

function getjson(){
    var json = [];
    var checkedBoxes = $('input[name="checkedList"]:checked').map(function() {
        return this.value;
    }).get();
var checkedBoxes1 = $('input[name="checkedList1"]:checked').map(function() {
        return this.value;
    }).get();

    json.push({"id":checkedBoxes});
    json.push({"Flap":checkedBoxes1});
    document.getElementById("jsonObj").value = json;
}

In MyForm.Java:

private JsonObject jsonObjct;
//getters and setters for jsonObjct

I am collecting the information of the checked values in the form of json and saving it in "jsonObjct" in MyForm and trying to retrieve the value in my controller using:

myForm.getJsonObjct();

Can anyone please help me out with this.Thanks in advance.

Upvotes: 1

Views: 1389

Answers (1)

boukobba adil
boukobba adil

Reputation: 140

firstly this [{"id":["4"]},{"Flap":["NA"]}] is a jsonArray. if you can use org.json jar that will be better and very simple.

import org.json.JSONArray;

public class GsonExample {

    public static void main(String[] args) {
        String jsonString="[{\"id\":[\"4\"]},{\"Flap\":[\"NA\"]}]";
        JSONArray arr= new JSONArray(jsonString);
        System.out.println(arr.getJSONObject(0).getJSONArray("id").get(0));
    }
}

The output is 4. i guess that what you need.

Upvotes: 1

Related Questions