正如标题所示,我在使用Android Studio中的asynctask解析来自URL的JSON数据时遇到问题。我一直收到Null Object Reference错误,但是如果我在Eclipse Enterprise项目中使用下面的代码(没有asynctask代码,只是常规应用程序),我就能很好地解析JSON。此外,互联网可以在我的模拟器上运行,因为我可以在网络浏览器上访问Google。你们能指出我如何克服这个问题的正确方向吗?我已经尝试了所有我能想到的东西,而且我只是感到困惑,因为代码在常规Eclipse Java Application项目中工作,但在Android Studio中不起作用。
Asynctask代码: @覆盖 protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); 的setContentView(R.layout.activity_buy_item);
class CallDBQuery extends AsyncTask<URL, Void, Item> {
protected Item doInBackground(URL...url) {
try {
URL urls = new
URL("XXX");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
//Item Items = mapper.readValue(urls, Item.class);
return mapper.readValue(urls, Item.class);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Item Items) {
TextView fieldTxt = (TextView)
findViewById(R.id.View2);
fieldTxt.setText(Items.getItems().get(0).GetTitle().toString());
}
}
try {
URL url = new
URL("XXX");
new CallDBQuery().execute(url);
}
catch(Exception e) {
e.printStackTrace();
}
}
注意:注释掉Items Item = mapper.readValue()部分因为我是 接收&#34;冗余变量消息&#34;,但即使我使用这段代码,并返回&#34; Items&#34;,我仍然收到空对象参考
JSON:
{"Items":[{"Email":"jared.hart1@gmail.com","Description":"Surface Pro 4
for sale, in excellent condition, basically brand
new!","Phone":"4077603835","Title":"Surface Pro 4","Id":"1"},
{"Email":null,"Description":null,"Phone":null,"Title":"Macbook
Air","Id":"2"},{"Email":"jhart@radixx.com","Description":"Free Macbook
Air, I promise","Phone":"3433215565","Title":"Lenovo
Laptop","Id":"3"}]}
JSON Class Item:
public class Item {
@JsonProperty
private List<ItemDetails> Items = new ArrayList<ItemDetails>();
public List<ItemDetails> getItems() {return this.Items;}
public void setItems(List<ItemDetails> Items) {this.Items = Items;}
}
JSON Class ItemDetails:
public class ItemDetails {
@JsonProperty
private String Id;
@JsonProperty
private String Title;
@JsonProperty
private String Phone;
@JsonProperty
private String Email;
@JsonProperty
private String Description;
public String GetId() {return this.Id;}
public void SetId(String Id) {this.Id = Id;}
public String GetTitle() {return this.Title;}
public void SetTitle(String Title) {this.Title = Title;}
public String GetPhone() {return this.Phone;}
public void SetPhone(String Phone) {this.Phone = Phone;}
public String GetEmail() {return this.Email;}
public void SetEmail(String Email) {this.Email = Email;}
public String GetDescription() {return this.Description;}
public void SetDescription(String Description) {this.Description =
Description;}
}
答案 0 :(得分:0)
我想通了!!在我的Manifest文件中,我在应用程序标记内部。我调试了我的应用程序,并发现由于Internet安全权限异常,我从代码的catch块中获取Null值。在应用程序标记之外添加代码后,一切正常!