jsonObject的一些方法

1.從前端傳過來的數字,默認是Integer類型不能直接用Long接收前端

錯誤寫法: java

  報錯:Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Longweb

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

正確寫法:後端

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

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

最簡便的:spa

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

 

與jsonObject.optLong()相似還有blog

  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); }

相關文章
相關標籤/搜索