Xstream为List <object> </object>生成了json响应

时间:2013-04-19 19:03:00

标签: javascript jquery ajax json xstream

我正在使用Xstream为我的应用程序生成JSON。我想使用JSON来支持ajax。当我尝试

     xstream.alias(classAlias, jsonModel.getClass()); //Note classAlias="records"
responseStream.println(xstream.toXML(jsonModel));

其中jsonModel实际上是实体对象的列表。实体类名称是人员,它位于“ beans ”包中,因此完全限定名称将是 bean。人即可。好 Person类具有id,name,age等属性。

生成的JSON是

   {"records":[{"beans.Person":[{"id":21,"name":"Name21","username":"Username21","password":"password21","age":41,"sex":true},{"id":22,"name":"Name22","username":"Username22","password":"password22","age":42,"sex":true},{"id":23,"name":"Name23","username":"Username23","password":"password23","age":43,"sex":true},{"id":24,"name":"Name24","username":"Username24","password":"password24","age":44,"sex":true},{"id":25,"name":"Name25","username":"Username25","password":"password25","age":45,"sex":true},{"id":26,"name":"Name26","username":"Username26","password":"password26","age":46,"sex":true},{"id":27,"name":"Name27","username":"Username27","password":"password27","age":47,"sex":true},{"id":28,"name":"Name28","username":"Username28","password":"password28","age":48,"sex":true},{"id":29,"name":"Name29","username":"Username29","password":"password29","age":49,"sex":true},{"id":30,"name":"Name30","username":"Username30","password":"password30","age":50,"sex":true}]}]}

我使用了jquery的$ .getJSON来获取按钮点击事件的响应。我每次都检查了“成功”的状态,因此效果很好。当我尝试访问第一条记录时会发生问题,即人员的信息,如身份证,用户名等。

我在Javascript中编写语句

<script>
        $(document).ready(function() {
            $("input").click(function(){
                $.getJSON("http://mylocalhost:8080/Paging/paging/records?page=3",function(data,status){

                    alert(status);
                    alert(data.records[0].beans.Person[0].id);
                });
            });
        });

    </script>

第一次警报有效但第二次没有。

然后javascript会在遇到错误时停止工作。我可以猜到的是,在记录数组中,Person对象后面是包名。这可能是因为浏览器可能在记录数组中寻找bean对象而不是因为beans.Person在这种情况下是一个单一的原子名称,如上所示。但不确定?

如果这确实存在问题,那么我如何停止/控制XStream将对象的名称命名为 classname (person)而不是 package.classname (beans.person )因为它是默认命名的。

或者如果生成的JSON对象中的一切正常,那为什么我看不到预期的结果呢?为什么简单的第二个警告声明不起作用。

1 个答案:

答案 0 :(得分:0)

我得到了我要使用的答案

 alert(data.records[0]["beans.Person"][0].id);

而不是

 alert(data.records[0].beans.Person[0].id);

有用的链接

http://www.javascripttoolbox.com/bestpractices/#squarebracket