javascript 解析 json字符串方法

    技术2022-05-20  48

    var jsonString = "{Test:[{"userName":"sortt"},{"userName":"sortt1"}, {"userName":"sortt2"},{"userName":"sortt3"},{"userName":"sortt4"}, {"userName":"sortt5"},{"userName":"sortt6"}]}"; var dataobj=eval("("+jsonString+")"); alert(dataobj.Test.length); $.each(dataobj.Test,function(idx,item){ if(idx==0){return true;} alert("name:"+item.userName); })

     

    另外,附上一个在网上看到的从数据库查询数据,然后解析成json字符串的方法

    1.从数据库查询某个对象,例如,User,将多个User  add到List<User>中

    2.写一个方法:toJson(User user)

    public String toJSON(Test test){ return "{/"userName/":/""+test.getUsername()+"/"}"; }

    3.在网页上通过一个Bean去查询,得到这个List<user>,然后调用上面的方法输出成json字符串

    String json = "{User:["; for (int index = 0; index < list.size(); index++) { json = json + dao.toJSON(list.get(index)); if (index != (list.size() - 1)) { json = json + ","; } json = json + "]}"; }

    4.可以定义一个全局变量去存储得到的json Stirng值:如下

    <p id="jsonLocation" style="display: none" mce_style="display: none"><%=json%></p>

    5.然后上面的jsonString就可以这样得到:

    var jsonString=$("#jsonLocation").html();


    最新回复(0)