【问题标题】:Problem in converting Java Object to JSON in Spring Boot在 Spring Boot 中将 Java 对象转换为 JSON 的问题
【发布时间】:2020-11-21 08:17:22
【问题描述】:

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

package com.we.springmvcboot.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.we.springmvcboot.Model.Todo;
import com.we.springmvcboot.Service.TodoService;
import com.we.springmvcboot.Service.UserNotesRepository;

import antlr.collections.List;

import java.sql.Date;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TodoController {
@Autowired
private TodoService TodoRepo;


@RequestMapping(value = "/loginUser", method = RequestMethod.POST)
        public @ResponseBody HashMap<String, Object> createPerson(@RequestParam("email") String email) {
                

    System.out.println(todoservice.findByEmail(email));
    HashMap<String, Object> map = new HashMap<>();
   map.put("Status", 200);
    map.put("Message", "Request Successful");
    
    map.put("Data", todoservice.findBySql(1));
     
    return map;

}
}
package com.we.springmvcboot.Service;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.we.springmvcboot.Model.OrderResponse;
import com.we.springmvcboot.Model.Todo;


@Repository
public interface TodoRepo extends JpaRepository<Todo, Integer> {
    @Query(value="SELECT Notes.notesID, Notes.Title, Notes.Message, Notes.Date, UserNotes.UserID from 
    UserNotes JOIN Notes on UserNotes.NotesID=Notes.NotesID where userID=?1", nativeQuery=true)
    List<Object> getSqlbyuserID(int user);
    

}



我得到的输出为

{
    "Status": 200,
    "Message": "Request Successful",
    "Data": [
        [
             1,
            "First Note",
            "By Rohan",
            "2017-03-03",
             1
        ],
        [
            2,
            "Second Note",
            "By Rohan",
            "2017-03-03",
            1
        ]
    ]
}

但我想要以下格式的输出

{
“Status” : 200/400,
“Message” : “Request Successful”,
    “Data” : {
        “userNotes” : [
            {
                “notesID” : 1,
                “title” : “abc”,
                “message” : “content”,
                “date” : 29/07/2020
                "userID : 1
 },
            {
                “notesID” : 2,
                “title” : “abc”,
                “message” : “content”,
                “date” : 28/07/2020
                "userID" : 2
             }
]
}

【问题讨论】:

  • “ 和 ” 不是有效的 JSON 引用字符,它们必须是 "。 --- 200/400 不是一个有效的 JSON 值,它必须是一个字符串:"200/400"。 --- 29/07/2020 不是一个有效的 JSON 值,它必须是一个字符串:"29/07/2020"。 --- 如果您希望数据是 JSON 对象,那么您需要创建一个用于存储数据的类,并带有适当名称和类型的字段。

标签: java mysql spring-boot


【解决方案1】:

如果您只是 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.

    }
}

TodoService.java

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);
    }
}

UserRepository.java

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);
}

User.java

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;
    }
}

我希望,你会得到你正在寻找的答案。

【讨论】:

    【解决方案2】:

    您正在从List&lt;Object&gt; getSqlbyuserID(int user); 发送对象列表并将其设置为map.put("Data", todoservice.findBySql(1));。

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

    【讨论】:

    • ... 很可能,OP 只需将List&lt;Object&gt; 更改为List&lt;Todo&gt;。当 OP 已有模型类时,无需创建新模型类(请参阅JpaRepository&lt;Todo, Integer&gt; 和 import com.we.springmvcboot.Model.Todo;)。
    猜你喜欢
    • 2017-08-23
    • 2019-04-19
    • 2018-07-10
    • 2022-11-09
    • 2015-09-15
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多