我有一些代码包含下一层:
@JsonRootName("users")
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "age")
private Integer age;
@Column(name = "code")
private Integer code;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
public class UsersDao {
@Autowired
public SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
public List<User> findAll(){
Query<User> query = session().createQuery("from User", User.class);
return query.list();
}
}
public class UsersService {
@Autowired
public UsersDao usersDao;
@Transactional(readOnly = true)
public List<User> findAllUsers(){
return usersDao.findAll();
}
}
@Controller
@RequestMapping("/users")
public class UsersController {
@Autowired
UsersService usersService;
@RequestMapping(value = "/all", produces = {"application/json"})
@ResponseBody
public List<User> getAllUsers() {
return usersService.findAllUsers();
}
}
当我尝试获取请求localhost:8080 / testreactproject / users / all
时[{"id":1,"firstName":"John","lastName":"Doe","age":28,"code":916},{"id":2,"firstName":"Jane","lastName":"Doe","age":27,"code":985}]
但我想用根元素
获得下一个json{"users":[{"id":1,"firstName":"John","lastName":"Doe","age":28,"code":916},{"id":2,"firstName":"Jane","lastName":"Doe","age":27,"code":985}]}
这是对我的pom.xml文件的依赖
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.10</version>
</dependency>
我知道我应该创建ObjectMapper类的实例,然后再次配置这个实例
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)
我尝试在控制器类(方法getAllUsers)中添加此代码,但它对我不起作用。 我做错了什么?
答案 0 :(得分:0)
问题解决了。我为类User(实体层)创建了类包装器,并为包装器绑定了根元素。所以我得到了一个正确的json对象。 看起来像是:
<iframe id="myIframe" src="https://stackoverflow.com/questions/45525117/get-iframe-content-by-using-javascript#"></iframe>
<script>
const myFrame = document.getElementById('myIframe');
myFrame.addEventListener('load', (evt) => {
console.log(evt.target === myFrame);
console.log(evt.target);
});
</script>