本文介绍了Ajax响应无法解析LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将Localdate作为Ajax响应的一部分传递给jquery数据表. LocalDate字段不显示其值.而是打印[object,Object].显然,这意味着LocalDate没有反序列化.可以请一个人解释如何反序列化Localdate以便正确显示它.以下是我的Jquery代码:

I need to pass Localdate as part of the Ajax response to jquery datatables. LocalDate field does not display its value. Instead it prints [object,Object]. Obviously, it means LocalDate was not deserialized. Can some one please explain how to deserialize Localdate to display it properly.Below is my Jquery Code:

var table = $("#example").DataTable({
            "bProcessing" : true,
            "bServerSide" : true,
"sAjaxSource" : "jsonSource.web",
            "aoColumns" : [
            {
                "mData" : "name"
            }, {
                "mData" : "position"
            }, {
                "mData" : "office"
            }, {
                "mData" : "phone"
            }, {
                "mData" : "salary"
            }, {
                "mData" : "dob"
            }
            ],
            columnDefs : [ {
                targets : [ 5 ],
                render : function(data, type, row) {
                    var json = JSON.stringify(data);
                    var date = JSON.parse(json);
                    console.log("json: " + json + "date : " + row);
                    return data;
                }
            }
            } ]
            });

服务器端代码:

@RequestMapping(value = "/springPaginationDataTables.web", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody String springPaginationDataTables(HttpServletRequest  request) throws IOException {

        //Fetch search parameter
        String searchParameter = request.getParameter("sSearch");
        final String sortColumn = request.getParameter("iSortCol_0");
        final String sortOrder = request.getParameter("sSortDir_0");
        //Fetch Page display length
        Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));
        //Fetch the page number from client
        Integer pageNumber = 0;
        if (null != request.getParameter("iDisplayStart"))
            pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/pageDisplayLength)+1;
        System.out.println("sSearch : "+searchParameter);
        System.out.println("pageDisplayLength : "+pageDisplayLength);
        System.out.println("pageNumber : "+pageNumber);
        System.out.println("iSortCol_0 : "+sortColumn);
        System.out.println("sSortDir_0 : "+sortOrder);

        List<Person> personsList = new ArrayList<Person>();
                Person person2 = new Person();
                person2.setName("John Landy");
                person2.setPosition("System Architect");
                person2.setSalary("$320,800");
                person2.setOffice("NY");
                person2.setPhone("999999999");
                person2.setStart_date("05/05/2010");
                person2.setDob(LocalDate.parse("1989-07-09"));
personsList.add(person2);
//apply server side search
//apply server side sort
//BuildDataTable object
        PersonJsonObject personJsonObject = new PersonJsonObject();
        //Set Total display record
        personJsonObject.setiTotalDisplayRecords(500);
        //Set Total record
        personJsonObject.setiTotalRecords(500);
        personJsonObject.setAaData(personsList);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json2 = gson.toJson(personJsonObject);

        return json2;
        }

推荐答案

我解决了.必须从codehaus扩展SimpleModule以实现LocalDate的序列化/反序列化.下面是我的代码:

I solved it. had to extend SimpleModule from codehaus to implement serialisation/deserialisation for LocalDate. Below is my code:

public class LocalDateSimpleModule extends SimpleModule{

    public LocalDateSimpleModule(String name, Version version) {
        super(name, version);
        addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
            @Override
            public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
                ToStringSerializer.instance.serialize(value, jgen, provider);
            }
        });
        addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
            @Override
            public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
                ToStringSerializer.instance.serialize(value, jgen, provider);
            }
        });
        addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() {
            @Override
            public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                return LocalDate.parse(jp.getText());
            }
        });
        addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
            @Override
            public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                return LocalDateTime.parse(jp.getText());
            }
        });
    }
}

在servlet-springs.xml中注册此模块

Register this module in servlet-springs.xml

<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>

<bean name="localDateModule" class="packge.LocalDateSimpleModule">
    <constructor-arg name="name" value="LocalDateModule" />
    <constructor-arg name="version" ref="version" />
</bean>
<bean name ="version" class="org.codehaus.jackson.Version">
    <constructor-arg value="1"/>//some value
    <constructor-arg value="1"/>
    <constructor-arg value="1"/>
    <constructor-arg value=" "/>
</bean>

这篇关于Ajax响应无法解析LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:41