开发中遇到的一些版本兼容问题-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();
}
}
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();
}
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories