您的位置:首页 > 移动开发 > Objective-C

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

2015-06-05 15:39 411 查看
例子:

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 注意