开发中遇到的一些版本兼容问题-JsonObject

来源:互联网 发布:xvideos软件中文版下载 编辑:程序博客网 时间:2024/06/02 05:26

例子:

public void show(){                String str="\ufeff{\"code\":\"00\"}"; try {JSONObject job=new JSONObject(str);System.out.println(job.getString("code"));} catch (JSONException e) { e.printStackTrace();} }



低版本的json没有对BOM头( 字符\ufeff,经常遇到有服务器返回字符的时候出现这个)做处理,于是会出现:

org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject



高版本的json构造方法为:

public JSONObject(String json) throws JSONException {        this(new JSONTokener(json));}public JSONTokener(String in) {        // consume an optional byte order mark (BOM) if it exists        if (in != null && in.startsWith("\ufeff")) {            in = in.substring(1);        }        this.in = in;}

低版本的json构造方法为:


public JSONObject(String json) throws JSONException {        this(new JSONTokener(json)); }public JSONTokener(String in) {        this.in = in;    }


故编写json解析类的时候需要注意加上\ufeff字符的处理,以便兼容低版本的手机系统。

如:

 public void show(){                 String str="\ufeff{\"code\":\"00\"}"; if(str!=null && str.startsWith("\ufeff")){ str=str.substring(1); } try {JSONObject job=new JSONObject(str);System.out.println(job.getString("code"));} catch (JSONException e) { e.printStackTrace();}  } 









0 0
原创粉丝点击