您的位置:首页 > 本地本地

如何获取前端传过来的json对象?

admin2024-05-02人已围观

一、如何获取前端传过来的json对象?

获取前端传过来的json对象

代码如下

public JSONObject getRequestContent(HttpServletRequest req) {

JSONObject data = null;

try {

InputStream is = req.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(is, utf-8));

String line = null;

StringBuffer content = new StringBuffer();

while ((line = br.readLine()) != null) {

System.out.println(line);

content.append(line);

System.out.println(content);

}

String reqStr = content.toString().trim();

if (StringUtils.isEmpty(reqStr)) {

return new JSONObject();

}

if (reqStr.contains(=)) {

reqStr = reqStr.replaceAll(=, :);

}

if (!reqStr.startsWith({)) {

reqStr = { + reqStr;

}

if (!reqStr.endsWith(})) {

reqStr = reqStr + };

}

data = JSONObject.fromObject(reqStr);

} catch (Exception e) {

e.printStackTrace();

return new JSONObject();

}

return data;

}

二、js获取返回的json

jsonarray.属性名就好了

三、js如何动态获取数据库中的json数组,取出后又怎么输出呢?

js要组合其他程序才能获取数据库中的数据吧

然后使用以下两种方法之一把json转为object使用

<script>

var b = '{t: 0, b: adfjierg}';

try{

var a = (new Function('return' + b))();

document.write(typeof(a));

}catch(e){

document.write('error');

}

var c=eval('('+b+')');

document.write(typeof(c));

</script>

四、javascript如何循环读取JSON数据

服务端后台返回到客户端的JSON格式字符串:<br>var str = '[{&quot;uname&quot;:&quot;王强&quot;,&quot;day&quot;:&quot;2010/06/17&quot;},{&quot;uname&quot;:&quot;王海云&quot;,&quot;day&quot;:&quot;2010/06/11&quot;}]';<br>我们把它转换成JSON对象:var jsonList=eval(&quot;(&quot;+str+&quot;)&quot;);这时候如果以用断点跟踪查看这个jsonList对象,其实你会发现,他的长度为2,即jsonList.length=2。它的每一项都是一个单独的JSON对象。请看下图:<br>这时候假设我们不知道&quot;uname&quot;和&quot;day&quot;这两个key值,我们开始对jsonList执行循环操作。<br>for(var i=0;i&lt;jsonList.length;i++){<br>alert(&quot;key:&quot;+key+&quot;,value:&quot;+jsonList[i][key]);}}这样我们就可以轻松的获取我所需要的key值和value值了

很赞哦! ()

上一篇:存在苹果里的音乐还能用什么软件播放'>谈谈自媒体、新媒体和融媒体

下一篇:返回列表'>返回列表

随机图文