【问题标题】:Json Hash map view in jsp [closed]jsp中的Json Hash映射视图[关闭]
【发布时间】:2018-12-25 16:55:34
【问题描述】:

我需要解决我的问题,我的类型 Json 我返回 {"1":"Position1","2":"Position2"} 但我需要 [{"id":1,"name":Position1},{"id":2,"name":Position2}]

这是我的方法控制器:

@GET
@RequestMapping(value = "/getPositiontMapByDepartmentId/{departmentId}")
@ResponseBody
public String getPositiontMapByDepartmentId(Employee employee, Model model,
                                     @PathVariable("departmentId") int departmentId) {
    Gson gson = new Gson();
    List<Position> positionListById = positionService.findAllPositionsByDepartmentId(departmentId);
    Map<Integer, String> positiontMapByDepartmentId = preparePositionMapByDepartmentId(departmentId);
    positionListById.toArray();
    return gson.toJson(positiontMapByDepartmentId);
}
public Map<Integer, String> preparePositionMapByDepartmentId(int departmentId) {
    Map<Integer, String> positiontMapByDepartmentId = new HashMap<Integer, String>();
    List<Position> positionListById = positionService.findAllPositionsByDepartmentId(departmentId);
    for( Position position : positionListById){
        positiontMapByDepartmentId.put(position.getId(),position.getName());
    }
    return positiontMapByDepartmentId;
}

我的 jsp 和 Java 脚本

$(document).ready(
        function() {

            $('#departmentSelect').on("change", function () {
                var departmentId = $("#departmentSelect option:selected").val();
                    $.ajax({
                        type: "GET",
                        url: "/admin/getPositiontMapByDepartmentId/"+departmentId,
                        success: function (result) {
                            alert(result);
                            var result = JSON.parse(result);
                            var position = "";
                            for(var i = 0; i<result.length; i++){
                               position+= '<option value="' + result[i].id + '">' + result[i].name +'</option>';
                            }
                            $('#positionSelect').html(position);
                        }
                    });
            });
        });

当我收到{"1":"Position1","2":"Position2"} 时,我的 JS 可以改进对 html 的选择

【问题讨论】:

    标签: javascript java json spring


    【解决方案1】:

    getPositiontMapByDepartmentId 不返回数组,而是返回地图。因此,要获取一个数组,请将地图转换为一个集合,然后调用 toArray()

    在方法中使用以下返回值。

    return gson.toJson(positiontMapByDepartmentId.entrySet().toArray());
    

    【讨论】:

    • 谢谢它的工作!!!
    猜你喜欢
    • 2018-03-21
    • 2013-07-08
    • 2018-10-02
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多