此次使用的是alibaba的fastjson:jar包为fastjson-1.2.7.jar

参考:https://www.qingtingip.com/h_229797.html

思路:由于此次接收到的json数据格式为:{"list":[{"tHumidity":0,"tLightIntensity":0,"tTemperature":0,"tSerialNumber":"02001"},{"..........]}

   即{key: value(value为数组)},需要先提取出value,value为JSONArray类型,再对value数组进行遍历,再通过强转为JSONObject

   从而对数组元素中的json的键值进行读取。

alibaba的json的pom依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
     JSONObject json= new JSONObject();
JSONArray list = new JSONArray();
BufferedReader br;
String jsonStr = null;
String jsonStr2 = null;
try {
br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) {
sb.append(line);
}
json= JSONObject.parseObject(sb.toString());
jsonStr = JSONObject.toJSONString(json);
list = json.getJSONArray("list");
jsonStr2 = JSONArray.toJSONString(list); } catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
System.out.println(list);
//System.out.println(jsonStr.substring(0,jsonStr.length()-1));
// System.out.println(jsonStr); System.out.println("======================"); // List<MyClass> list = JSONObject.parseArray(jsonStr, MyClass.class);
for (int i = 0; i < list.size();i++){
JSONObject object = (JSONObject)list.get(i);
// System.out.println(object);
Zhongyao zhongyao = new Zhongyao();
zhongyao.setId(UUIDUtil.uuid());
zhongyao.settSerialNumber(object.getString("tSerialNumber"));
zhongyao.settTemperature((object.getDouble("tTemperature") == null) ? 0 :object.getDouble("tTemperature"));
zhongyao.settHumidity((object.getDouble("tHumidity") == null) ? 0 : object.getDouble("tHumidity"));
zhongyao.settLightIntensity((object.getDouble("tLightIntensity") == null) ? 0 : object.getDouble("tLightIntensity"));
zhongyao.settSoilTemperature((object.getDouble("tSoilTemperature") == null) ? 0 :object.getDouble("tSoilTemperature"));
zhongyao.settSoilHumidity((object.getDouble("tSoilHumidity") == null) ? 0 : object.getDouble("tSoilHumidity"));
zhongyao.settSoilPh((object.getDouble("tSoilPh") == null) ? 0 : object.getDouble("tSoilPh"));
//(json.getDouble("tSoilPh") == null)
System.out.println("+++++++++++++id:"+zhongyao.getId()+"tSerialNumber:"+zhongyao.gettSerialNumber()+
"tTemperature:"+zhongyao.gettTemperature()+"tHumidity:"+zhongyao.gettHumidity()+"tLightIntensity:"+zhongyao.gettLightIntensity()
+"tSoilTemperature:"+zhongyao.gettTemperature()+"tSoilHumidity:"+zhongyao.gettHumidity()+"tSoilPh:"+zhongyao.gettSoilPh());
// } //4. 调用Service保存
DataService service = new DataServiceImpl();
service.addData(zhongyao);
}
05-11 22:48