我正在JSF中构建一个Java应用程序,该应用程序向API发出请求会获取JSON并用JSON信息填充表格...
这是代码:
pam[12]
第67行-> @ManagedBean(name = "logic", eager = true)
@SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
public void connect() {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
}catch(Exception e) {System.out.println(e);}
try {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
jo = (JSONObject) cat.get(0);
jo.get("cif");
System.out.println(jo.get("cif"));
}catch(Exception e){System.out.println(e);}
}
private String cif;
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() {
}
public Logic(String cif) throws ParseException {
this.cif = cif;
connect();
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}
它在Netbeans中给了我这个错误:未报告的异常ParseException;必须被抓住或宣布被抛出。 我尝试将其包含在try catch中,但是它在代码的其他部分给出了其他错误...该怎么办才能运行app?
预先感谢
答案 0 :(得分:1)
据我了解,您尝试过类似的操作
try {
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
问题是,该行不在方法内部,因此您不能在其中使用try...catch
。
解决此问题的一种快速方法是将初始化放在static
块中
public class Logic {
final static private ArrayList<Logic> logics;
static {
try {
logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
// rest of your class...
}
但是,老实说,我不得不怀疑您为什么将logics
声明为static
。从您的其余代码中看不出来。另外,我看到您有一个非静态的getLogics()
方法。因此,我想说的是,如果真的没有理由将其声明为static
,只需使其成为非静态变量并在构造函数中对其进行初始化,就可以在其中使用try...catch
来满足您的需求。>