繁体   English   中英

在 Z38008DD81C2F4D7985ECF6E0CE 中将 Java Object 转换为 JSON 时出现问题

[英]Problem in converting Java Object to JSON in Spring Boot

我最近开始使用 Spring Boot。 我在以所需格式将 Java Object 转换为 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);
    

}



我得到 output 作为

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

但我想要以下格式的 output

{
“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
             }
]
}

如果您只是 Spring 引导的初学者,那么我建议您遵循以下编码结构。 您将获得预期的 output 简单方法。

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

用户.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;
    }
}

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

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

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

暂无
暂无

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

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