简体   繁体   English

如何在 SpringBoot 中返回列表

[英]How to return list in SpringBoot

code below return me list of two objects like this:下面的代码返回两个对象的列表,如下所示:

[
    {
        value: "ssss",
    },
    {
        value: "ssss",
    },
]

but i want to return list like this:但我想像这样返回列表:

{
    value1:"xxxx",
    value2:"xxxx"
}

here is my code这是我的代码

    @Override
    public List<OrderModel> getOrderByCode(UserEntity user) throws ErrorException {

        List<UserEntity> userOrder = userRepository.findByUserAndOrderCodeIn(user, Arrays.asList(OrderCodes.OK, OrderCodes.DONE));

        List<OrderModel> om = new ArrayList<OrderModel>();
        for(UserAnswerEntity userAnswerEntity : userAnswers){
            OrderModel orderModel = new OrderModel();
            orderModel.setValue(userAnswerEntity.getValue());

            om.add(orderModel );
        }

        return om;
    }
public class OrderModel{

    String value;

//get,set
}

can someon tell me how can i return only list like above?有人可以告诉我如何只返回上面的列表吗?

You are trying to make a custom response.您正在尝试做出自定义响应。 One of the possible way is this一种可能的方法是

Map<String,String> map = new HashMap<String,String>();
map.put("key1", "value1");
map.put("key2", "value2");

System.out.println(map.toString().replace("{", "[").replace("}", "]"));

Change the return type of getOrderByCode() to string and convert your List object to JSON string.将 getOrderByCode() 的返回类型更改为字符串,并将您的 List object 转换为 JSON 字符串。

private static final ObjectMapper jsonMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
return jsonMapper.writeValueAsString(om);

for you example, you can use Map instead of List例如,您可以使用Map而不是List

try this:尝试这个:

  AtomicInteger index = new AtomicInteger()
  Function<UserAnswerEntity, String> createIndex = (userAnswer) -> "value" + index.getAndIncrement();
  return userAnswers.stream().collect(Collectors.toMap(createIndex, UserAnswerEntity::getValue));

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

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