将JSON作为响应Spring Boot返回

问题描述 投票:3回答:4

我试图得到休息响应作为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。

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

spring spring-boot spring-data-jpa spring-data spring-data-rest
4个回答
0
投票

您需要将json属性定义为JsonNode,以便jackson可以将其读回和转发,但标记为@Transient,因此JPA不会尝试将其存储在数据库中。

然后你可以为JPA编写getter / setter代码,你可以在这里从JsonNode转换为String。你定义了一个将getJsonString转换为JsonNode json的getter String。那个可以映射到表列,比如'json_string',然后你定义一个setter,你从JPA接收String并将其解析为jsonNode,这将是jackson的可用,然后jackson将它转换为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是在gettters定义的,因为我们需要指示JPA使用getJsonString而JPA需要一致性所以所有列的getter必须用@Columns标记。


1
投票

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

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

并将getData字符串包装为响应

    public class StringResponse {

        private String response;

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

}

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属性转换为您想要的结果。谢谢


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

}

© www.soinside.com 2019 - 2024. All rights reserved.