gpt4 book ai didi

java - 如何更改Json格式?

转载 作者:行者123 更新时间:2023-12-02 09:46:57 26 4
gpt4 key购买 nike

我想更改 Json 的显示格式。

我尝试打印整个 Item 对象,它正在打印所有属性(看起来正常)。我尝试更改 Controller 和服务以返回字符串,并且尝试操作字符串,但我认为这不是解决问题的好方法。一定是更好的东西。

{  
"requestedUrl":"https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items":[
{
"id":"-SYM4PW-YAgC",
"volumeInfo":{
"title":"The Religion of Java",
"authors":[
"Clifford Geertz"
],
"industryIdentifiers":[
{
"type":"ISBN_10",
"identifier":"0226285103"
},
{
"type":"ISBN_13",
"identifier":"9780226285108"
}
],
"readingModes":{
"text":true,
"image":true
},
"pageCount":392,
"printType":"BOOK",
"categories":[
"Religion"
]
}
}
]
}

BookController.java

@CrossOrigin
@RestController
@RequestMapping("/")
public class BookController {

private BookService service;

public BookController(BookService service) {
this.service = service;
}

@GetMapping("book/{isbn}")
public Item getBook(@PathVariable String isbn) {
return service.findBookByISBN(isbn);
}

}

BookService.java

public class BookService {

public BookService() throws IOException {
}


public Item findBookByISBN(String isbn) {
// listOfItems taking json file from json file and making List<Item> to itarate over
for (Item item : listOfItems) {
if (item.getVolumeInfo().getIndustryIdentifiers().get(0).getIdentifier().equals(isbn)) {
return item;
}
}
return null;
}
}

当然我有 POJO 类...

对于findBookByISBN(9780226285108)json answear 是

{
"title":"The Religion of Java",
"authors":[
"Clifford Geertz"
],
"industryIdentifiers":[
{
"type":"ISBN_10",
"identifier":"0226285103"
},
{
"type":"ISBN_13",
"identifier":"9780226285108"
}
],
"readingModes":{
"text":true,
"image":true
},
"pageCount":392,
"printType":"BOOK",
"categories":[
"Religion"
]
}

但我想让我的 json 像这样:

{  
"title":"The Religion of Java",
"printType":"BOOK",
"pageCount":392,
"authors":[
"Clifford Geertz"
],
"categories":[
"Religion"
]
}

最佳答案

您可以使用数据传输对象 (DTO) 并仅发送所需的信息作为响应。

 {  
"title":"The Religion of Java",
"printType":"BOOK",
"pageCount":392,
"authors":[
"Clifford Geertz"
],
"categories":[
"Religion"
]
}

在这种情况下,您可以编写像这样的 DTO

 class NameYouWant{
String title;
String printType;
Integer pageCount;
List<String> authors = new ArrayList<>();
List<String> categories = new ArrayList<>();
//generate getters and setters of the above data members.
}

现在,当您发送响应时,请在该 dto 中设置数据,如下所示:-创建对象

 public Item findBookByISBN(String isbn) {
for (Item item : listOfItems) {
if (item.getVolumeInfo().getIndustryIdentifiers().get(0).getIdentifier().equals(isbn)) {
NameYouWant na = new NameYouWant();
na.setTitle(item.getTitle());
na.setPrintType(item.getPrintType());
na.setPageCount(item.getPageCount());
na.SetAuthors(item.getAuthors());
na.SetCategories(item.getCategories());
return na;
}
}
return null;
}

通过这种方式,您可以在前端仅发送所需的数据。

关于java - 如何更改Json格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56574015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com