簡體   English   中英

將JSON作為響應Spring Boot返回

[英]Returning JSON as Response Spring Boot

我試圖得到休息響應作為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。

任何幫助,將不勝感激。 謝謝 !!

在你的控制器中添加json響應:

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

並將getData字符串包裝為響應

    public class StringResponse {

        private String response;

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

}

像這樣改變你的一些模型類

@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屬性轉換為您想要的結果。 謝謝

您需要將json屬性定義為JsonNode,以便jackson可以將其讀回和轉發,但標記為@Transient因此JPA不會嘗試將其存儲在數據庫中。

然后你可以為JPA編寫getter / setter代碼,你可以在這里從JsonNode轉換為String。 您定義了一個getter getJsonStringJsonNode json轉換為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 column是在gettters中定義的,因為我們需要指示JPA使用getJsonString並且JPA需要一致性所以所有列的getter必須用@Columns標記。

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

}

將您的數據庫答案從findAll轉換為對象類型列表,如(Sometype類型列表),然后返回數據。 這將解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM