jsonObject的一些方法

1.从前端传过来的数字,默认是Integer类型不能直接用Long接收

错误写法: 

  报错:Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

  Long demendid=(Long)jsonObject.get("demandId");

正确写法:

  Long demendid=((Integer)jsonObject.get("demandId")).longValue();

  Long demendidd=((Number)jsonObject.get("demandId")).longValue();

最简便的:

  Long demandId=jsonObject.optLong("demandId");

 

与jsonObject.optLong()类似还有

  jsonObject.optInteger()

  jsonObject.optInt()

  jsonObject.optBoolean()

  jsonObject.optString()

  jsonObject.optJSONArray()

  

转换为对象

Demand demand = (Demand) JSONObject.toBean(demandJson, Demand.class);

2.前端传来JSON字符串有值 但无法转为java对象。

  A.前端传来的属性包含集合属性,可直接将整体转为json字符串传过来后端用对象接收 ,加上@RequestBody,前端属性名字和后端接收的对象的属性名字一样就可以将对应的List集合传到后端。

 

  b.其他情况如 后台是字符串接收,或者集合是某个属性对象的属性,则只能先转为json字符串,然后擦护脑后台再转回来。

 

----------------------------------

 

需要网后台传一个拼装好的json字符串,刚开始各种错误 如var message=“{message:msg,sid: '18212341252',toAll: 'false'}“;

在花括号外面加了引号,所以报错。

花括号里面引号不必须加,花括号外面肯定不能加引号,然后还要用JSON.stringify(),否则后台收到的就是object无法转换

正确写法;

function send() {
  var msg= document.getElementById('text').value;
  var message={message:msg,
      sid: '18212341252',
      toAll: 'false'};
  var s=JSON.stringify(message)

  websocket.send(s);
}

 

 

 


posted @ 2019-04-10 10:08  小梅子呀  阅读(1213)  评论(0编辑  收藏  举报