简体   繁体   English

创建一个包含数组数组的 json 响应

[英]Create a json response containing array of array

Response required需要回复

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

Model 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.我觉得列表列表不适合实现所需的 json 响应。但我无法用列表替换它,其中 CustomObject 将包含 2 个 integer 成员变量。 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..因为它将更改响应的格式并将响应作为包含 CustomObject 类型的对象列表而不是列表列表的数据发送。

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达到所需 output 的最简单方法是

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

and use this code for serilization with Jackson JSON并使用此代码与 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]]} output 字符串将根据您的需要{"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.您自己的com.fasterxml.jackson.databind.ser.std.StdSerializer<T> Timeseries class 的继任者。

UPDATE:更新:

Just find out the easiest way to reach your needed string for class只需找出最简单的方法来获取 class 所需的字符串

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

Note data field has to be either public or have a getter.注意data字段必须是public的或有一个 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]]}将打印{"data":[[1234,55],[1264,45],[1334,56]]}

You can use a list of Arrays of size 2.您可以使用大小为 2 的 Arrays 列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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