【问题标题】:Play framework 1.2.5 - Trying to post a Person object to a controllerPlay framework 1.2.5 - 尝试将 Person 对象发布到控制器
【发布时间】:2012-06-02 04:46:12
【问题描述】:

我可能错过了一些东西,因为我还没有完全理解一些基础知识。 在我的控制器中,我有类似于

functiona(Person person){
System.out.println(p.firstName);
}

视图有以下内容

$.post("/validatePerson",{person: [{name:"first",value:"last"}]},function(result){
alert('done');
}

看起来好像信息正在传递,但成员未填充。 我也尝试添加以下类型绑定器

@Global
public class PersonJsonObjectBinder implements TypeBinder<Person> {     
    @Override     
    public Person bind(String name, 
                        Annotation[] annotations, 
                        String value, Class actualClass, 
                        Type genericType) throws Exception 
                        {                               
                        return new Gson().fromJson(value, Person.class);
                        }
                    //return new JsonParser().parse(value) ;}
}

非常感谢您的帮助。

【问题讨论】:

  • 你确定 person 应该是一个数组吗?我认为应该是一个对象:{person: {name:"first",value:"last"}}

标签: java jquery json controller playframework-1.x


【解决方案1】:

如果您想直接绑定到控制器参数,您需要将 Person 数据作为请求 uri 的一部分传入。

$.post("/validatePerson?person.firstname=john&person.lastname=doe",function(result){
alert('done');

}

查看参数 person.firstname 如何匹配参数名称 person 和属性。

为了从 Json 绑定,您可以将主体作为 json 元素获取并使用 GSON 构建器进行反序列化。类似于以下内容

JsonElement jsonElement = new JsonParser().parse(body);
Person person = new GsonBuilder().create().fromJson(jsonElement,Person.class)

json 属性再次需要匹配 Person 类的属性,例如

{person: [{firstname:"john",lastname:"doe"}]}

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多