spring-mvc中通过json的参数和继承

发布于 2024-11-01 10:41:24 字数 2104 浏览 0 评论 0原文

我需要建议。我试图将对象列表作为参数传递给用 spring-mvc 3 编写的方法控制器,所有这些都使用 ajax。这些对象是小部件类的后代。 代码

我将首先向您展示ajax 调用的

function buildWidget(obj){
    var result = null;
    switch(obj.className){
    case 'text':
        result = {
            x:obj.control.x
            ,y:obj.control.y
            ,height: obj.control.height
            ,width: obj.control.width
            ,text: obj.text
        };
        break;
    case 'youtube':
        result = {
            x:obj.control.x
            ,y:obj.control.y
            ,height: obj.control.height
            ,width: obj.control.width
            ,videos: obj.videos
        };
        break;
    }
    return result;
}

var all = new Array();
            for(i=0;i<figures.size;i++)
                all.push(buildWidget(figures.data[i].widget));
            jQuery.getJSON("pages/save.html", { widgetsList: jQuery.toJSON(all) }, function(myresult) {
                alert('ok');
            });

:服务器端

public class WidgetAdapter {

    private int x;
    private int y;
    private int width;
    private int height;
// getters and setters
}

public class TextWidgetAdapter extends WidgetAdapter {

    private String text;

    // getters and setters

}

public class YoutubeWidget extends WidgetAdapter{

    private String videos;

    // getters and setter
}

控制器(这里的问题),

@RequestMapping(value = "/pages/save",method=RequestMethod.GET)
    public @ResponseBody String save(@RequestParam String widgetsList){
        Type listType = new TypeToken<List<WidgetAdapter>>() {}.getType();
        List<WidgetAdapter> adapters = new Gson().fromJson( widgetsList, listType);
        for(WidgetAdapter a :adapters){
            System.out.println(a.getX());
        }
        return new Gson().toJson(new ActionResult("msg"));
    }

因此,当调用方法控制器时 Gson 创建一个列表适配器,所有元素都是 WidgetAdapter 类,而不是 TextWidgetAdapter 或 YoutubeWidget。有办法实现吗?我的意思是传递参数作为类的元素后代列表并由 Gson 正确转换?

谢谢,我希望能说清楚。英语不是我的母语。

PD:我正在以一种好的方式做这一切,或者说存在更好的方式。

I need an advice. I'm trying to pass a list of objects as parameters to a method controller written with spring-mvc 3, all this with ajax. These objects are decendants of a widget class. i will show you the code first

the ajax call:

function buildWidget(obj){
    var result = null;
    switch(obj.className){
    case 'text':
        result = {
            x:obj.control.x
            ,y:obj.control.y
            ,height: obj.control.height
            ,width: obj.control.width
            ,text: obj.text
        };
        break;
    case 'youtube':
        result = {
            x:obj.control.x
            ,y:obj.control.y
            ,height: obj.control.height
            ,width: obj.control.width
            ,videos: obj.videos
        };
        break;
    }
    return result;
}

var all = new Array();
            for(i=0;i<figures.size;i++)
                all.push(buildWidget(figures.data[i].widget));
            jQuery.getJSON("pages/save.html", { widgetsList: jQuery.toJSON(all) }, function(myresult) {
                alert('ok');
            });

the server side

the classes

public class WidgetAdapter {

    private int x;
    private int y;
    private int width;
    private int height;
// getters and setters
}

public class TextWidgetAdapter extends WidgetAdapter {

    private String text;

    // getters and setters

}

public class YoutubeWidget extends WidgetAdapter{

    private String videos;

    // getters and setter
}

the controller (the problem here)

@RequestMapping(value = "/pages/save",method=RequestMethod.GET)
    public @ResponseBody String save(@RequestParam String widgetsList){
        Type listType = new TypeToken<List<WidgetAdapter>>() {}.getType();
        List<WidgetAdapter> adapters = new Gson().fromJson( widgetsList, listType);
        for(WidgetAdapter a :adapters){
            System.out.println(a.getX());
        }
        return new Gson().toJson(new ActionResult("msg"));
    }

so, when the method controller is called Gson creates a List adapters, all elements are of class WidgetAdapter and not TextWidgetAdapter or YoutubeWidget. Is there a way to acheive that?? i mean pass parameters as list of element decendants of a class and be transformed correctly by Gson?

Thanks, i hope be clear. english is not my native language.

pd: i´m doing all of this in a good way or better way exists.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那伤。 2024-11-08 10:41:24

好的!我告诉你我是如何解决这个问题的。请告诉我你的意见。
我创建了一个自定义反序列化器(在这里我创建了具体实例)。这是代码:

@RequestMapping(value = "/pages/save",method=RequestMethod.GET)
    public @ResponseBody String save(@RequestParam String widgetsList){
        GsonBuilder gson = new GsonBuilder();
        // register the custom deserializer for my WidgetAdapterClass
        gson.registerTypeAdapter(WidgetAdapter.class, new WidgetDeserialization());
        Type listType = new TypeToken<List<WidgetAdapter>>() {}.getType();
        // create gson an deserialize object
        List<WidgetAdapter> adapters = gson.create().fromJson( widgetsList, listType);
        // just for testing proposes
        for(WidgetAdapter a :adapters){
            System.out.println(a.getWidth());
        }

        return new Gson().toJson(new ActionResult("Ok"));
    }

具体的反序列化器

public class WidgetDeserialization implements JsonDeserializer<WidgetAdapter> {

    /***
     * factory method for custom WidgetAdapter
     * @param json
     * @return WidgetAdapter
     */
    private WidgetAdapter getWidget(JsonObject json){
        WidgetAdapter adapter = null;
        //obtain widget class. Util for instanciate concrete class
        String className = json.get("className").getAsString();
        // create concrete classes and set concrete atributes
        if("text".equals(className)){
            adapter = new TextWidgetAdapter(json.get("text").getAsString());
        }else if("youtube".equals(className)){
            adapter = new YoutubeWidgetAdapter(json.get("videos").getAsString());
        }
        // if adapter is created common atributes are set
        if(adapter!=null){
            adapter.setHeight(json.get("height").getAsInt());
            adapter.setWidth(json.get("width").getAsInt());
            adapter.setX(json.get("x").getAsInt());
            adapter.setY(json.get("y").getAsInt());
        }
        return adapter;
    }

    @Override
    public WidgetAdapter deserialize(JsonElement element, Type arg1,
            JsonDeserializationContext arg2) throws JsonParseException {
        JsonObject obj = element.getAsJsonObject();
        return getWidget(obj);
    }

}

我希望它有帮助

Ok! I tell you how i solved this problem. Please, tell me your opinion.
I created a custom deserializer (here i create concretes instances). Here is the code:

@RequestMapping(value = "/pages/save",method=RequestMethod.GET)
    public @ResponseBody String save(@RequestParam String widgetsList){
        GsonBuilder gson = new GsonBuilder();
        // register the custom deserializer for my WidgetAdapterClass
        gson.registerTypeAdapter(WidgetAdapter.class, new WidgetDeserialization());
        Type listType = new TypeToken<List<WidgetAdapter>>() {}.getType();
        // create gson an deserialize object
        List<WidgetAdapter> adapters = gson.create().fromJson( widgetsList, listType);
        // just for testing proposes
        for(WidgetAdapter a :adapters){
            System.out.println(a.getWidth());
        }

        return new Gson().toJson(new ActionResult("Ok"));
    }

the concrete deserializer

public class WidgetDeserialization implements JsonDeserializer<WidgetAdapter> {

    /***
     * factory method for custom WidgetAdapter
     * @param json
     * @return WidgetAdapter
     */
    private WidgetAdapter getWidget(JsonObject json){
        WidgetAdapter adapter = null;
        //obtain widget class. Util for instanciate concrete class
        String className = json.get("className").getAsString();
        // create concrete classes and set concrete atributes
        if("text".equals(className)){
            adapter = new TextWidgetAdapter(json.get("text").getAsString());
        }else if("youtube".equals(className)){
            adapter = new YoutubeWidgetAdapter(json.get("videos").getAsString());
        }
        // if adapter is created common atributes are set
        if(adapter!=null){
            adapter.setHeight(json.get("height").getAsInt());
            adapter.setWidth(json.get("width").getAsInt());
            adapter.setX(json.get("x").getAsInt());
            adapter.setY(json.get("y").getAsInt());
        }
        return adapter;
    }

    @Override
    public WidgetAdapter deserialize(JsonElement element, Type arg1,
            JsonDeserializationContext arg2) throws JsonParseException {
        JsonObject obj = element.getAsJsonObject();
        return getWidget(obj);
    }

}

I hope it helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文