我是Grafana和Spring Boot的新手。我正在尝试创建一个Spring Boot应用程序,并使用Grafana SimpleJSON插件从我的Spring Boot api中获取数据并创建图形。(仅供参考,与我的问题不太相关-我在这里遵循说明https://grafana.com/grafana/plugins/grafana-simple-json-datasource/)
现在我只是硬编码数据到我的春季启动应用程序,但我卡住了得到正确的JSON格式我需要。
我想要的:
[
{
"columns":[
{"text":"Time","type":"time"},
{"text":"Country","type":"string"},
{"text":"Number","type":"number"}
],
"rows":[
[1234567,"SE",123],
[1234567,"DE",231],
[1234567,"US",321]
],
"type":"table"
}
]
实现这一点的最佳方法是什么?
到目前为止,我尝试创建一个自定义类,也尝试使用Map(如何在Springboot中返回JSON响应?)。但在这两种方法中都遇到了同样的问题-"行"中的数据;有不同的类型(例如[1234567,"SE",123])。我怎么知道呢?@PostMapping("/query")
public ??? getData() {
...
}
谢谢!
您需要为这种情况定义正确的返回类型。
我想应该这样做:
@PostMapping("/query")
public List<Item> getData() {
List<Item> response = new ArrayList<>();
Item item = new Item();
item.type = "table";
Column col1 = new Columne("Time", "time");
item.columns.add(col1);
// add other columns
item.rows.add(new Object[] {1234567, "SE", 123})
// add other rows
response.add(item);
return response;
}
class Item {
public String type;
public List<Column> columns = new ArrayList<>();
public List<Object[]> rows = new ArrayList<>();
}
class Column {
public String text;
public String type;
public Column(String text, String type) {
this.text = text;
this.type = type;
}
}
我想最简单的方法是定义DTO类。
public class MyObject {
private List<TextType> columns;//you have to define TextType class
private List<Object[]> rows;
private String type;
//Getters and setters
}
如果在行中有混合类型,则不能定义类型;但是,您可以在运行时对其进行调整。否则,如果rows元素有3个元素,您可以定义您的类型。
public class MyObject2 {
private int i1;
private String s1;
private int i2;
//Getters and setters
//Define your own format that print i1, s1, i2 instead of {"i1": i1, "s1":s1, "i2":i2}
}