返回JSON作为响应Spring Boot

时间:2019-03-06 02:02:18

标签: spring spring-boot spring-data-jpa spring-data spring-data-rest

我试图以json的形式获取休息响应,而不是以字符串的形式。

控制器

@RestController
@RequestMapping("/api/")
public class someController{

  @Autowired
  private SomeService someService;

  @GetMapping("/getsome")
  public Iterable<SomeModel> getData(){
    return someService.getData();
  }
}

服务

@Autowired
private SomeRepo someRepo;

public Iterable<someModel> getData(){
  return someRepo.findAll();
}

存储库

public interface SomeRepo extends CrudRepository<SomeModel,Integer>{

}

模型

@Entity
@Table(name="some_table")
public class SomeModel{

  @Id
  @Column(name="p_col", nullable=false)
  private Integer id;
  @Column(name="s_col")
  private String name
  @Column(name="t_col")
  private String json;   // this column contains json data

  //constructors, getters and setters
}

当我运行 localhost:8080 / api / getsome 时,我得到:

[
 {
    "p_col":1,
    "s_col":"someName",
    "t_col":" 
{\r\n\t"school_name\":\"someSchool\",\t\r\n\t"grade\":"A\",\r\n\t\"class\": 
 [{\"course\":"abc",\t"course_name\":\"def" }]}"
  }
]

字段 t_col 返回的是字符串而不是json。如何获得json对象作为响应?

对于数据库,三列是int,varchar和varchar。

任何帮助将不胜感激。谢谢!!

5 个答案:

答案 0 :(得分:1)

像这样更改您的某些模型类

@Entity
@Table(name="some_table")
public class SomeModel {

    @Id
    @Column(name="p_col", nullable=false)
    private Integer id;
    @Column(name="s_col")
    private String name
    @Column(name="t_col")
    private String json;   // this column contains json data

    @Column(name = "t_col", columnDefinition = "json")
    @Convert(attributeName = "data", converter = JsonConverter.class)
    private Map<String, Object> json = new HashMap<>();

    //constructors
    //getters and setters
}

编写一个json转换器类。

@Converter
public class JsonConverter
                    implements AttributeConverter<String, Map<String, Object>> 
{


    @Override
    public Map<String, Object> convertToDatabaseColumn(String attribute)
    {
        if (attribute == null) {
           return new HashMap<>();
        }
        try
        {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(attribute, HashMap.class);
        }
        catch (IOException e) {
        }
        return new HashMap<>();
    }

    @Override
    public String convertToEntityAttribute(Map<String, Object> dbData)
    {
        try
        {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(dbData);
        }
        catch (JsonProcessingException e)
        {
            return null;
        }
    }
}

它将将数据库json属性转换为您想要的结果。谢谢

答案 1 :(得分:0)

在您的控制器中添加json响应:

 @RequestMapping(value = "/getsome", method = RequestMethod.GET, produces = "application/json"

然后将getData字符串包装为响应

    public class StringResponse {

        private String response;

        public StringResponse(String s) { 
           this.response = s;
        }

}

答案 2 :(得分:0)

  @RequestMapping(value = "/getsome", method = RequestMethod.POST, consumes = 
  "application/json;")
 public @ResponseBody
  ModelAndView getSome(@RequestBody List<Map<String, String>> request) {
 request.stream().forEach(mapsData->{
    mapsData.entrySet().forEach(mapData -> {
      System.Out.Println("key :"+mapData.getKey() + " " + 
        " value : " +mapData.getValue());
    });
  }
});
return new ModelAndView("redirect:/home");

}

答案 3 :(得分:0)

您需要将json属性定义为JsonNode,以便杰克逊可以将其向前和向后读取,但是标记为@Transient,因此JPA不会尝试将其存储在数据库中。

然后,您可以为JPA编写getter / setter的代码,在其中将JsonNode转换为String来回转发。您定义了将getJsonString转换为JsonNode json的getter String。可以将其映射到表列(例如'json_string'),然后定义一个setter,从JPA接收String并将其解析为JsonNode(杰克逊可使用),然后杰克逊将其转换为json对象不是您提到的字符串。

@Entity
@Table(name = "model")
public class SomeModel {

  private Long id;
  private String col1;

  //  Attribute for Jackson 
  @Transient
  private JsonNode json;

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId() {
    return id;
  }

  @Column(name ="col1")
  public String getCol1() {
    return col1;
  }

  // Getter and setter for name

  @Transient
  public JsonNode getJson() {
    return json;
  }

  public void setJson(JsonNode json) {
    this.json = json;
  }

  // Getter and Setter for JPA use
  @Column(name ="jsonString")
  public String getJsonString() {
    return this.json.toString();
  }

  public void setJsonString(String jsonString) {
    // parse from String to JsonNode object
    ObjectMapper mapper = new ObjectMapper();
    try {
      this.json = mapper.readTree(jsonString);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

注意,@Column是在gettter上定义的,因为我们需要指示JPA使用getJsonString,并且JPA需要一致性,因此所有列的getter必须标记为@Columns

答案 4 :(得分:0)

将您的数据库答案从findAll投射到一个对象类型列表,例如(某种类型的列表),然后返回数据。这将解决您的问题。