Converting Java Map object to Json array

时间:2018-03-22 23:36:35

标签: java json spring-mvc gson

My Spring MVC Controller is returning LinkedHashMap. I want to convert to Json Array in order to pass in AJAX. Also Suggest me the return type of getTime method

Controller code:

@RequestMapping("/activeSlots")
@ResponseBody
public String getTime(@RequestParam("date") String date){

    AvailableTimeSlot ts = new AvailableTimeSlot();
    List<String> bookedTime = ts.getInfo(date);
    LinkedHashMap<String,String> availTimeSlots = ts.availTime(bookedTime);
    Gson gson = new Gson();

    String json = gson.toJson(availTimeSlots);

        return json;
}`

Ajax Call Code

$( "#idDateField" ).change(function() {
         var dateval = $( "#idDateField" ).val();
         var sendData = {dateval: dateval}
         $.ajax({

                //url :"/activeSlots?date="+dateval ,
                 url :"activeSlots?date=" + dateval ,
            //      method : GET,
            //  contentType: 'application/json',
                success: function (data) {
                    alert("coming..")

                    alert(obj.length);
                        $("#nameid").val(data);                     

                           $("#idTimefield").val(data);

                        },
                        error:function(data) {
                            alert("error:"+data.val);
                        }

            });
        });`

1 个答案:

答案 0 :(得分:1)

我的工作;这是解决方案 Java控制器代码:

@RequestMapping("/activeSlots")
@ResponseBody
public String getTime(@RequestParam("date") String date){

    AvailableTimeSlot ts = new AvailableTimeSlot();
    List<String> bookedTime = ts.getInfo(date);
    LinkedHashMap<String,String> availTimeSlots = ts.availTime(bookedTime);

    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(availTimeSlots);

    return json;
}

Ajax调用JSP

$( "#idDateField" ).change(function() {
         var dateval = $( "#idDateField" ).val();
         var sendData = {dateval: dateval}
         $.ajax({
                 url :"activeSlots?date=" + dateval ,
                success: function (data) {
                    alert(data);
                    $('#idTimefield').empty();
                    var times=JSON.parse(data);
                    var values= Object.values(times);
                    var keys = Object.keys(times);


                    for(i=0 ; i<values.length;i++){
                        $('#idTimefield').append('<option value="' + keys[i] + '">' + values[i] + '</option>');
                    }


                        },
                        error:function(data) {
                            alert("error:"+data.val);
                        }               
            });
        });     
});