当前位置: 代码迷 >> 综合 >> net.sf.json.JSONException: A JSONArray text must start with ‘[‘ at character
  详细解决方案

net.sf.json.JSONException: A JSONArray text must start with ‘[‘ at character

热度:85   发布时间:2023-11-19 21:25:24.0

错误背景

后端返回json数据给前端页面报错


错误代码

package cn.com.service;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import net.*;
import org.*;
import cn.com.bean.User;
@Repository(value="regedit")
@Scope("prototype")
public class Regedit implements ModelDriven<User>{
@Autowired
private SessionFactory sf;
@Autowired
private User user;
@Transactional
public String regedit_user(){//获取session对象String toast="用户名已存在,请重新输入";	HttpServletResponse response = ServletActionContext.getResponse();//设置response输出json便于调试response.setCharacterEncoding("utf-8");PrintWriter out;try {out = response.getWriter();JSONArray json=JSONArray.fromObject(toast);out.write(json.toString());out.flush();out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "success";
}
public User getModel() {return user;
}
}

报错的原因

把一个object类型的变成json数组的形式,必须要有[]这个标志存在

 

解决方案

1、在字符串里面添加[]进去

2、用JSONObject

JSONArray json=JSONArray.fromObject(toast);
         out.write(json.toString());

把改成

        JSONObject json=new JSONObject();
         json.put("tom", toast);     

  相关解决方案