gpt4 book ai didi

Java,将 JSON 数组存储到类并从其他类调用它

转载 作者:太空宇宙 更新时间:2023-11-04 06:28:06 26 4
gpt4 key购买 nike

我试图从另一个类中的类中提取数据并用数据填充 JPanel,但由于某种原因它不起作用。

这是完整的restConnector 类,我在其中提取JSON 数据。据我所知,这工作得很好。

public class restConnector {

private static final Logger LOGGER = LoggerFactory.getLogger(restConnector.class);

private static final restConnector INSTANCE = new restConnector();


public static restConnector getInstance() {
return restConnector.INSTANCE;
}

private restConnector(){
}

private static String user = "ss";
private static String pwd = "ee


public static String encode(String user, String pwd) {
final String credentials = user+":"+pwd;
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(credentials.getBytes());
}


//Open REST connection
public static void init() {
restConnector.LOGGER.info("Starting REST connection...");


try {

Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));

WebResource webResource = client.resource("https://somewebpage.com/

String url = "activepersonal";






ClientResponse response = webResource
.path("api/alerts/")
.queryParam("filter", ""+url)
.header("Authorization", "Basic "+encode(user, pwd))
.header("x-api-version", "1")
.accept("Application/json")
.get(ClientResponse.class);


if (response.getStatus() != 200) {

}else{
restConnector.LOGGER.info("REST connection STARTED.");
}


String output = response.getEntity(String.class);



ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new MyNameStrategy());

try {
List<Alert> alert = mapper.readValue(output, new TypeReference<List<Alert>>(){});



} catch (JsonGenerationException e) {

e.printStackTrace();

} catch (JsonMappingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

} catch (Exception e) {

e.printStackTrace();

}


}

public void close() {

}

}

但是,当我尝试在另一个类中提取数据时,它只从refreshData()方法内的system.out.print中给出空值。这是应该打印数据的代码

   public class Application{


Alert alerts = new Alert();


public Application() {
refreshData();
}

private void initComponents() {
restConnector.init();
refreshData();
}

private void refreshData() {
System.out.println("appalertList: "+alerts.getComponentAt(0));
}
}

这是我的警报类

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_EMPTY)
public class Alert {

private int pasID;
private String status;
private boolean shared;
private String header;
private String desc;

public int getPasID() {
return pasID;
}

public void setPasID(int pasID) {
this.pasID = pasID;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
public boolean isShared() {
return shared;
}

public void setShared(boolean shared) {
this.shared = shared;
}

public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}

@Override
public String toString() {

StringBuilder sb = new StringBuilder();
sb.append("\n***** Alert Details *****\n");
sb.append("PasID="+getPasID()+"\n");
sb.append("Status="+getStatus()+"\n");
sb.append("Shared="+isShared()+"\n");
sb.append("Header="+getHeader()+"\n");
sb.append("Description="+getDesc()+"\n");
sb.append("*****************************");

return sb.toString();

}

public String getComponentAt(int i) {

return toString();
}

}

我对此感到有点迷失,并且已经被困在这里几天了,因此非常感谢所有帮助。感谢您提前提供的帮助。

编辑:稍微格式化代码并删除 NullPointerException,因为它不再发生。

最佳答案

正如评论中所述:

Me: In your first bit of code you have this try { List<Alert> alert.., but you do absolutely nothing with the newly declared alert List<Alert>. It this where the data is supposed to be coming from?

OP: I'm under the impression that that bit of code is the one that pushes the JSON Array to the Alert.class. Is there something I'm missing there?

Me: And what makes you think it does that? All it does is read the json, and the Alert.class argument is the class type argument, so the mapper know the results should be mapped to the Alert attributes when it creates the Alert objects. That's how doing List<Alert> is possible, because passing Alert.class decribes T in List<T>. The List<Alert> is what's returned from the reading, but you have to determine what to actually do with the list. And currently, you do absolutely nothing with it

您可能想稍微更改一下类。

这绝不是一个好的设计,只是一个让它发挥作用的示例。我会花一些时间坐下来思考一下您想要的restConnector得到充分利用

话虽如此,您可以拥有 List<Alert> alerts; restConnector中的类(class)成员类(class)。并为其提供 setter/getter

public class restConnector {

private List<Alert> alerts;

public List<Alert> getAlerts() {
return alerts;
}
...
}

然后,当使用映射器反序列化时,值分配给 private List<Alert> alerts 。您正在做的是声明一个新的本地范围列表。所以而不是

try {
List<Alert> alert = mapper.readValue...

改为这样做

try {
alerts = mapper.readValue

现在类成员被分配了一个值。所以在 Application类你可以做类似的事情

public class Application {

List<Alert> alerts;
restConnector connect;

public Application() {
initComponents();
}

private void initComponents() {
connector = restConnector.getInstance();
connector.init();
alerts = connector.getAlerts();
refreshData();
}

private void refreshData() {
StringBuilder sb = new StringBuilder();
for (Alert alert : alerts) {
sb.append(alert.toString()).append("\n");
}
System.out.println("appalertList: "+ sb.toString());
}
}

现在您可以访问Alert已在列表中。

但是让我重申一下:这是一个可怕的设计。对于其中之一,您限制了 init方法一次调用,其中只能获取一个并且只能获取一种资源。如果其余服务需要访问不同的资源怎么办?你已经提出了铁定的要求,所以你不能。

花一些时间思考一些好的 OOP 设计,其中的类可以用于不同的场景。

关于Java,将 JSON 数组存储到类并从其他类调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26503733/

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