我面临一个非常奇怪的错误,我无法解释,也许你可以帮助我:
我正在使用JSON,我有一个类用于将响应代码包装在JSON中,如 {“code”:“0”} :
public class Container {
int responseCode=0;
protected int _object_id=0;
public Container(String fromJSON){
_object_id=new Random().nextInt();
try {
setWithJSON(fromJSON);
} catch (Exception e) {
e.printStackTrace();
responseCode=-1;
}
}
protected JSONObject setWithJSON(String input) throws Exception{
JSONObject json = new JSONObject(input);
responseCode = json.getInt("code");
return json;
}
}
扩展该类我有另一个类来包装响应代码+一个网址: {“code”:“0”,“url_tag”:“http://good.url.com”} :
public class URLContainer extends Container {
private final String TAG="Test";
private String _url = "default_url";
public URLContainer(String fromJSON) {
super(fromJSON);
}
@Override
protected JSONObject setWithJSON(String input) throws Exception {
JSONObject json= super.setWithJSON(input);
_url=json.optString("url_tag", "no_url");
getUrl(); //Just for print the pointB
Log.e(TAG,"Point A ("+_object_id+"): url="+_url);
return json;
}
public String getUrl() {
Log.e(TAG,"Point B ("+_object_id+"): url="+_url);
return _url;
}
public void setUrl(String url) {
_url = url;
}
}
活动类:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String json="{\"code\":\"0\",\"url_tag\":\"http://good.url.com\"}";
URLContainer container = new URLContainer(json);
Log.e("adsads",""+container.getUrl());
}
,结果日志为:
E/Test(20264): Point B (-569874754): url=http://good.url.com
E/Test(20264): Point A (-569874754): url=http://good.url.com
E/Test(20264): Point B (-569874754): url=default_url
E/Final(20264): default_url
为什么最后一次调用会返回default_url而不是一个好的?
答案 0 :(得分:2)
这是因为URLContainer的构造函数中的super(fromJSON);
。发生了什么
setWithJSON(String input)
// _ url在返回的JSON对象中设置为您想要的值只需在创建该实例后的URLContainer实例上调用setWithJSON(String input)
。
答案 1 :(得分:1)
这将有效
.......
public Container(String fromJSON){
_object_id=new Random().nextInt();
// try {
// setWithJSON(fromJSON);
// } catch (Exception e) {
// e.printStackTrace();
// responseCode=-1;
// }
}
.......
活动:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String json="{\"code\":\"0\",\"url_tag\":\"http://good.url.com\"}";
URLContainer container = new URLContainer(json);
container.setWithJSON(json);
Log.e("adsads",""+container.getUrl());
}