用于将查询结果(数组)转换为JSON格式,
我尝试使用@ResponseBody
注释以及produces="application/json"
,但输出格式没有改变。
我也试过ObjectMapper()
,但是字符串格式的输出不是键值。我删除了我的试用版,但是我没有正常工作。现在我在这里添加了我当前的代码。
这是我的代码段。
InvestigatorModel
package com.demo.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="investigator")
public class InvestigatorModel implements Serializable{
private static final long serialVersionUID = 1L;
@Id
public Integer ninvestigatorid;
public String sinvestigatorname;
public Integer ninstid ;
public String stitle;
public Integer ntempinvestigatorid;
public Integer nempid;
//getter and setter
InvestigatorController
package com.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.demo.model.InvestigatorModel;
import com.demo.services.InvestigatorService;
@RestController
@RequestMapping("/SpaceStudy/SpaceAdmin")
public class InvestigatorController {
@Autowired
InvestigatorService investService;
@CrossOrigin(origins="*")
@GetMapping("/AccountMaintenance/LoadInvestigator")
public List<InvestigatorModel> findInvestigatorName()
{
return investService.findInvestigatorName();
}
}
InvestigatorService
package com.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.model.InvestigatorModel;
import com.demo.repository.InvestigatorRepository;
@Service
public class InvestigatorService
{
@Autowired
InvestigatorRepository investRepo;
public List<InvestigatorModel> findInvestigatorName()
{
return investRepo.findBySinvestigatorname();
}
}
InvestigatorRepository
package com.demo.repository;
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.demo.model.InvestigatorModel;
@Repository
public interface InvestigatorRepository extends JpaRepository<InvestigatorModel, Integer>
{
@Query("select invest.sinvestigatorname from InvestigatorModel as invest where invest.ninstid=60")
List<InvestigatorModel> findBySinvestigatorname();
}
我的输出就像这个
示例输出
[
{
"sinvestigatorname": "Bargman",
}
]
如何将此输出转换为JSON格式(键,值) 任何人都可以帮助我如何做到这一点
答案 0 :(得分:2)
当您使用JPA时,最简单的解决方案是:
@Query("select new map(invest.sinvestigatorname as sinvestigatorname) from InvestigatorModel invest where invest.ninstid=60")
List<InvestigatorModel> findBySinvestigatorname();
这会给你想要的结果。
请参阅文档here