简体   繁体   中英

Create a json response containing array of array

Response required

{
  "data" : [[1234, 55],[1264,45],[1334, 56]]
}

Model

Class Timeseries{
  private List<List<Integer>> data;
}

I don't feel List of List is appropriate to achive the json response required.. But I am unable to replace it with List, where CustomObject will contain 2 integer member variables. As it will change the format of the response and send the response as data containing list of objects of type CustomObject instead of list of list..

Please suggest an alternate approch

You can try like this,

class CustomObject {
    private int data1;
    private int data2;
    // getters & setters
}

Then you can modify your Timeseries as below,

private List<CustomObject> data;

The easiest way to reach your needed output is

class data extends ArrayList<List<Integer>> {
}

and use this code for serilization with Jackson JSON

data ts = new data();
ts.addAll(Arrays.asList(Arrays.asList(1234, 55), Arrays.asList(1264, 45), Arrays.asList(1334, 56)));

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String result = objectMapper.writeValueAsString(ts);

System.out.println(result);

The output string will be as you need {"data":[[1234,55],[1264,45],[1334,56]]}

But, seriously, the right way here is to implement for

class Timeseries {
    private List<List<Integer>> data;
}

your own com.fasterxml.jackson.databind.ser.std.StdSerializer<T> successor for Timeseries class.

UPDATE:

Just find out the easiest way to reach your needed string for class

class Timeseries {
   public List<List<Integer>> data;
}

Note data field has to be either public or have a getter.

And then code

Timeseries ts = new Timeseries();
ts.data = Arrays.asList(Arrays.asList(1234, 55), Arrays.asList(1264, 45), Arrays.asList(1334, 56));

ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(ts);
System.out.println(result);

will print {"data":[[1234,55],[1264,45],[1334,56]]}

You can use a list of Arrays of size 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM