Home > Net >  Java Spring Boot JSON Response
Java Spring Boot JSON Response

Time:07-02

I am new to Grafana and Spring Boot. I am trying to create a Spring Boot application, and use Grafana SimpleJSON plugin to get data from my Spring Boot APIs and create graphs. (Just for reference, not too relevant to my question - I'm following instructions here https://grafana.com/grafana/plugins/grafana-simple-json-datasource/)

Right now I am just hard-coding data into my Spring Boot App, but am stuck on getting the correct JSON format I need.

What I want:

[  
  {  
    "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"  
  }  
]  

What is the best way to implement this?

So far, I've tried to create a custom class, and also tried to just use Map (How to return JSON response in Springboot?). But encountered the same issue in both methods - data in "rows" have different types (e.g. [1234567,"SE",123]). How can I go by this?

@PostMapping("/query")
public ??? getData() {
    ...
}

Thanks!

CodePudding user response:

You need to define the correct return type for this case.

Somethink like this should work:

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

CodePudding user response:

I guess the easiest way is to define the DTO class.

    public class MyObject {
    private List<TextType> columns;//you have to define TextType class
    private List<Object[]> rows;
    private String type;
    
    //Getters and setters
}

If you have mixed types in rows you can not define type; however, you can adjust it on runtime. Otherwise, if the rows element has 3 elements you can define your type.

    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}
}
  • Related