gpt4 book ai didi

java - 列表仅填充 JSON 中的一行,应该填充多行

转载 作者:行者123 更新时间:2023-12-02 09:04:10 25 4
gpt4 key购买 nike

您好,我有一个 JSF 应用程序,它向 API 发出 GET 请求,获取 JSON,然后从该 JSON 获取元素并用它填充 JSF 数据表。我想用所有元素填充数据表,但只添加一个。

这是我的 Java 代码:

@ManagedBean(name = "logic", eager = true)
@SessionScoped
public class Logic {

static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;

private ArrayList<Logic> logics;
StringBuilder sb = new StringBuilder();
String cif2;

public void connect() {

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

private String cif;

public ArrayList<Logic> getLogics() {
return logics;
}

public Logic() throws ParseException {
connect();

JSONParser parser = new JSONParser();

jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
for(int i = 0; i < cat.size(); i++) {
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
}
}

public Logic(String cif) throws ParseException {
this.cif = cif;
}

public String getCif() {
return cif;
}

public void setCif(String cif) {
this.cif = cif;
}
}

我编写的用于插入的代码是这样的:

public Logic() throws ParseException {
connect();

JSONParser parser = new JSONParser();

jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
for(int i = 0; i < cat.size(); i++) {
jo = (JSONObject) cat.get(i);
cif2 = jo.get("cif").toString();
logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));
}

}

它对 json 执行 for 循环,但只添加最后一个值。

我想添加所有值

提前致谢

最佳答案

您应该初始化 logics带有空数组列表。

private ArrayList<Logic> logics = new ArrayList<>();

还有

替换logics = new ArrayList<Logic>(Arrays.asList(new Logic(cif2)));logics.add(new Logic(cif2));

关于java - 列表仅填充 JSON 中的一行,应该填充多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59962207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com