net.sf.json.JSONException: Object is null

问题:SSM前端jsp页面使用angular请求数据,后台Controller拿到了数据但是个别值是空的,因此报了此异常。

原来我懒得在controller封装json数据,直接使用的是第一种方式转换:

//	前端angular请求数据
	@ResponseBody
	@RequestMapping(value="showCar", method = RequestMethod.POST)
	public JSONArray showCar(@RequestBody(required=false)String requestJson,HttpSession session) {
		System.out.println("CarController.showCar() ran...");
//		从session中拿到UserId
		Integer userId =  (Integer) session.getAttribute("uId");
		System.out.println("从session中拿到的UserId:;"+userId);
		Car car = this.carService.findByUserId(userId);
		List<CarItem> carItemList = car.getCarItem();
		System.out.println("找到用户的购物车:");
		System.out.println(car);
//		第一种方式:car直接转为json格式
//		JSONArray jsonCar = JSONArray.fromObject(car);
//		第二种:
		JSONArray json = new JSONArray();
        for(CarItem item  : carItemList){
            JSONObject jo = new JSONObject();
            jo.put("trainName", item.getCaritemTrainName());
            jo.put("trainPrice",item.getCaritemTrainPrice());
            jo.put("trainImg", item.getCaritemTrainImg());              
            jo.put("trainCheck", item.getCaritemChecked()); 
            json.element(jo);
            System.out.println("JSONArray json==="+json);
            System.out.println(" JSONObject jo==="+jo);
        }
		return json;
	}

 

然后一直异常,jsp检查了好久

解决:后面就换成了第二种方式:前端需要啥我就装啥进去。。。

然后前端就拿到了


<script>
var app=angular.module("userCarApp" , [])
app.controller("myCar",function($scope,$http){ 
	$http({
		method : "POST",
		url : "http://localhost:8080/car/showCar"
	}).then(function(response) {
		$scope.car=response.data
	});		
})

</script>

 

感谢大神!参考自:https://blog.csdn.net/a954735254/article/details/81670695

不过有一个地方:

JSONArray 对象 里面要装JSONObject对象的时候, 我用上面的博客的put方法,但是不可行,可能是版本问题吧,我猜的

我的版本:

<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>

 

因此不用put(),改成:element()

json.element(jo);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

asjodnobfy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值