简体   繁体   English

如何从控制器读取作为排序列表返回的JavaScript对象的值

[英]How to read values of a JavaScript object returned as a sorted list from controller

I get a sorted list from my controller to jsp page. 我从控制器到jsp页面得到了一个排序列表。 I want to process this in javascript. 我想用javascript处理。

var foo = '${entityTypes}';

When I tried to loop this using a for in and read the values. 当我尝试使用for in循环并读取值时。 but, it reads each and every character of the strings available. 但是,它会读取可用字符串的每个字符。 I tried json parse and stringify too, but still I get the same result. 我也尝试了json解析和字符串化,但是仍然得到相同的结果。

var foo = '${entityTypes}';
alert(foo);

var str = JSON.stringify(foo);
var obj1 = JSON.parse(str); 
alert(obj1);    

for (var k in obj1) {
    if (obj1.hasOwnProperty(k)) {
        alert("Key is " + k + ", value is " + obj1[k]);
    }
}

As the Java-List is not automatically converted into JSON-format, the value of foo is entityList.toString() . 由于Java-List不会自动转换为JSON格式,因此foo的值是entityList.toString() What you have to do is, to convert the Java-List by yourself into JSON-format. 您要做的是,将Java-List自己转换为JSON格式。
But it is much cheaper to convert the entityList in the controller. 但是在控制器中转换entityList便宜得多。 gson or jackson for example are some nice Java libraries which do Entity-to-JSON-conversion. 例如, gsonjackson是一些不错的Java库,它们执行Entity-to-JSON转换。

I managed to get this done. 我设法做到了。 I found it is a string by the comment of VeXii. 通过VeXii的评论,我发现它是一个字符串。 Thanks Vexxi. 谢谢Vexxi。 As it's a string I used substr to remove unwanted characters. 因为它是一个字符串,所以我使用substr删除了不需要的字符。

    str = foo.substr(0, foo.length-1);
obj = str.substr(1);

this removed first and the last character. 这删除了第一个和最后一个字符。 That means the square bracket open and close. 这意味着方括号打开和关闭。

Then I used split method to get the string I wanted. 然后,我使用split方法获取所需的字符串。 Still I had an issue as my string came with a colon as the last character. 仍然有一个问题,因为我的弦上最后一个字符是冒号。 Again I removed the colon using spring methods available. 我再次使用可用的弹簧方法去除了结肠。

var arr = obj.split(',');

Thanks for your comments. 感谢您的意见。 That helped me to solve this. 那帮助我解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM