0

我正在使用杰克逊生成休息服务。我能够得到 JSON 响应

[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]

但我期待 Pojo 名称的响应指向如下响应

{"UserDetails":[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]}

这是我的实现类

@Service("userServices")
public class UserServiceImpl implements UserServices{

private UserServices userServices;

public UserServices getUserServices() {
    return userServices;
}
public void setUserServices(UserServices userServices) {
    this.userServices = userServices;
}

@Override
public List<UserDetails> getUser(UserDetails userDetails) {


    ObjectMapper mapper = new ObjectMapper();

    List<UserDetails> user = new ArrayList<UserDetails>();
    List<UserDetails> list = new ArrayList<UserDetails>();

    UserDetails userDetails2 = new UserDetails();
    userDetails2.setUserName("scott");
    userDetails2.setUserId(007);

    UserDetails userDetails3 = new UserDetails();
    userDetails3.setUserName("toe");
    userDetails3.setUserId(101);

    user.add(userDetails2);
    user.add(userDetails3);

    try{
    String jsonString = mapper.writeValueAsString(user);
    UserDetails[] userDetails4 = mapper.readValue(jsonString, UserDetails[].class);
    list = Arrays.asList(userDetails4);
    System.out.println(userDetails4);
    }catch (Exception e) {
        System.out.println(e);
    }
    return list;
}
}

这是我的pojo

public class UserDetails implements Serializable{

private String userName;
private int userId;

public UserDetails(){

}

 //getters and setters...
}

** 注意:** 我不想在域对象端使用任何注释。

4

3 回答 3

1

刚回来

用户详细信息响应:

public class UserDetailsResponse {

    private List<UserDetails> userDetails;
    // getter and setter

}

而不是 UserServiceImpl 中的 UserDetails 列表(大概然后在控制器中)。

于 2019-09-16T07:23:11.250 回答
0

您返回一个 UserDetails 列表,该列表将您的响应对象转换为 JSON 数组。为了获得您想要的结果,您需要创建一个容器类 (UserDetailsContainer),它具有 List 类型的属性 userDetails 并返回一个实例作为您的响应。

于 2019-09-16T07:13:19.597 回答
0

您可以objectMapper.writeValueAsString(aCustomMap)用于动态创建自定义 json 视图。

例子:

UserDetails userDetails2 = new UserDetails();
userDetails2.setUserName("scott");
userDetails2.setUserId(007);

UserDetails userDetails3 = new UserDetails();
userDetails3.setUserName("toe");
userDetails3.setUserId(101);

Map<String, List<UserDetails>> m = new HashMap<>();
m.put("UserDetails", Arrays.asList(userDetails2, userDetails3));

System.out.print(
    //This is what you need
    objectMapper.writeValueAsString(m)
);
//{"UserDetails":[{"userName":"scott","userId":7},{"userName":"toe","userId":101}]}
于 2019-09-16T07:33:18.767 回答