在Spring Boot中将Java对象转换为JSON时出现问题

在Spring Boot中将Java对象转换为JSON时出现问题,java,mysql,spring-boot,Java,Mysql,Spring Boot,我最近开始使用Spring Boot。在将Java对象转换为所需格式的JSON时,我遇到了一些问题 package com.we.springmvcboot.Controller; 导入org.springframework.beans.factory.annotation.Autowired; 导入org.springframework.stereotype.Controller; 导入org.springframework.ui.Model; 导入org.springframework.ui

我最近开始使用Spring Boot。在将Java对象转换为所需格式的JSON时,我遇到了一些问题

package com.we.springmvcboot.Controller;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Controller;
导入org.springframework.ui.Model;
导入org.springframework.ui.ModelMap;
导入org.springframework.web.bind.annotation.GetMapping;
导入org.springframework.web.bind.annotation.PathVariable;
导入org.springframework.web.bind.annotation.RequestBody;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入org.springframework.web.bind.annotation.RequestParam;
导入org.springframework.web.bind.annotation.ResponseBody;
导入org.springframework.web.bind.annotation.RestController;
导入org.springframework.web.servlet.ModelAndView;
导入com.fasterxml.jackson.databind.util.JSONPObject;
导入com.we.springmvcboot.Model.Todo;
导入com.we.springmvcboot.Service.TodoService;
导入com.we.springmvcboot.Service.UserNotesRepository;
导入antlr.collections.List;
导入java.sql.Date;
导入java.time.LocalTime;
导入java.util.HashMap;
导入java.util.Map;
@控制器
公共类TodoController{
@自动连线
私人TodoService TodoRepo;
@RequestMapping(value=“/loginUser”,method=RequestMethod.POST)
public@ResponseBody HashMap createPerson(@RequestParam(“电子邮件”)字符串电子邮件){
System.out.println(todoservice.findByEmail(email));
HashMap=newHashMap();
地图放置(“状态”,200);
map.put(“消息”,“请求成功”);
map.put(“数据”,todoservice.findBySql(1));
返回图;
}
}
package com.we.springmvcboot.Service;
导入java.util.List;
导入org.springframework.data.jpa.repository.JpaRepository;
导入org.springframework.data.jpa.repository.Query;
导入org.springframework.stereotype.Repository;
导入com.we.springmvcboot.Model.OrderResponse;
导入com.we.springmvcboot.Model.Todo;
@存储库
与Orepo的公共接口扩展了JpaRepository{
@查询(value=“从中选择Notes.notesID、Notes.Title、Notes.Message、Notes.Date、UserNotes.UserID
UserNotes在UserNotes.NotesID=Notes.NotesID上加入注释,其中userID=?1“,nativeQuery=true)
列出getSqlbyuserID(int用户);
}


我得到的输出是

{
“地位”:200,
“消息”:“请求成功”,
“数据”:[
[
1.
“第一个音符”,
“罗汉所作”,
"2017-03-03",
1.
],
[
2.
“第二注”,
“罗汉所作”,
"2017-03-03",
1.
]
]
}
但是我想要以下格式的输出

{
“状态”:200/400,
“消息”:“请求成功”,
“数据”:{
“用户注释”:[
{
“notesID”:1,
“标题”:“abc”,
“消息”:“内容”,
“日期”:2020年7月29日
“用户ID:1
},
{
“notesID”:2,
“标题”:“abc”,
“消息”:“内容”,
“日期”:2020年7月28日
“用户ID”:2
}
]
}

您正在从
list getSqlbyuserID(int-user);
发送对象列表,并将其设置为
map.put(“Data”,todoservice.findBySql(1));


您需要另一个类userNotes来保存getSqlbyuserID中的值并在map中进行设置。

如果您只是Spring Boot的初学者,那么我建议您使用以下编码结构。您可以通过简单的方式获得预期的输出

TodoController.java

package com.test.app.web;

import com.test.app.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
public class TodoController {

    @Autowired
    private TodoService todoService;


    @PostMapping("/loginUser")
    public @ResponseBody HashMap<String, Object> createPerson(@RequestParam("email") String email) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("Status", 200);
        map.put("Message", "Request Successful");
        map.put("Data", todoService.findByEmail(email));

        return map; // Here, I return any generic data object. instead of creating map for all the apis.

    }
}
package com.test.app.service;

import com.test.app.domain.User;
import com.test.app.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TodoService {

    @Autowired
    private UserRepository userRepository;

    public List<User> findByEmail(String email) {
        // Add your business logic here if you want to modify the fetched data.
        return userRepository.findAllByEmail(email);
    }
}
package com.test.app.repository;

import com.test.app.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    // Here Use, JPA naming convention to reduce the overhead of writing the native query.
    List<User> findAllByEmail(String email);
}
package com.test.app.domain;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "user")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "CREATION_TIMESTAMP", columnDefinition = "datetime")
    @Temporal(TemporalType.TIMESTAMP)
    private Date creationTimestamp;

    @Column(name = "LAST_UPDATED_TIMESTAMP", columnDefinition = "datetime")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdatedTimestamp;

    @Column(name = "name")
    private String name;

    @Column(name = "middelName")
    private String middelName;

    @Column(name = "lastName")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Column(name = "phoneNo")
    private String phoneNo;

    @Column(name = "contactPersonName")
    private String contactPersonName;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getCreationTimestamp() {
        return creationTimestamp;
    }

    public void setCreationTimestamp(Date creationTimestamp) {
        this.creationTimestamp = creationTimestamp;
    }

    public Date getLastUpdatedTimestamp() {
        return lastUpdatedTimestamp;
    }

    public void setLastUpdatedTimestamp(Date lastUpdatedTimestamp) {
        this.lastUpdatedTimestamp = lastUpdatedTimestamp;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMiddelName() {
        return middelName;
    }

    public void setMiddelName(String middelName) {
        this.middelName = middelName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getContactPersonName() {
        return contactPersonName;
    }

    public void setContactPersonName(String contactPersonName) {
        this.contactPersonName = contactPersonName;
    }
}

我希望你能得到你想要的答案。

不是有效的JSON引用字符,它们必须是
”200/400不是有效的JSON值,它必须是字符串:
200/40029/07/2020
不是有效的JSON值,它必须是字符串:
“29/07/2020”
——如果您希望数据是JSON对象,那么您需要创建一个用于存储数据的类,其中包含具有适当名称和类型的字段……最有可能的是,OP只需将
List
更改为
List
。当OP已经有一个模型类时,无需创建新的模型类(请参见
JpaRepository
导入com.we.springmvcboot.Model.Todo;
)。