简体   繁体   English

如何更改Json格式?

[英]How to changed Json format?

I want to change format of displaying Json. 我想更改显示Json的格式。

I tried to printg whole Item object and it's printing all attributes(looks normal). 我试图打印整个Item对象,它正在打印所有属性(看起来很正常)。 I tried to change controller and service to return String and I tried to manipulate String but it is not a good approach to the problem i think. 我试图更改控制器和服务以返回String,并且试图操纵String,但这不是解决我认为的问题的好方法。 Must be something better. 一定是更好的东西。

{  
   "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 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 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;
    }
}

Of Cours I have POJO class... 在Cours中,我有POJO课...

For findBookByISBN(9780226285108) json answear is 对于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"
            ]
}

But I want to make my json like this : 但我想像这样使我的json:

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

You can use a Data Transfer Object(DTO) and send only required information in response. 您可以使用数据传输对象(DTO)并仅发送所需的信息作为响应。

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

In this case you can write a DTO like 在这种情况下,您可以像

 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.
 }

now when you are sending response set the data in this dto like this:- create the object 现在,当您发送响应时,像下面这样在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;
}

In this way you can send only required data in the forntend. 通过这种方式,您只能在前端发送所需的数据。

create an interface with Getters of required fields and cast your original object to new Interface. 使用必填字段的Getter创建接口,并将原始对象转换为新的Interface。 When you serialize this object it will produce required result. 序列化此对象时,它将产生所需的结果。 eg 例如

class Body implements BriefBody {
        String content;
        String type;
        // ---Getters/Setters---
    }

interface BriefBody {
    String getContent();
}

BriefBody getBriefBody() {
    Body body = new Body();
    body.setContent("bodyContent");
    body.setType("bodyType");
    return body;
}

Result will have {"content":"bodyContent"}. 结果将包含{“ content”:“ bodyContent”}。

Create a new POJO for your expected response and in your BookService class (don't directly return the item) set the property and return. 为您的预期响应创建一个新的POJO,并在BookService类(不直接返回项目)中设置属性并返回。

Alternatively, create a new Item Object and set only the required property and return, assuming you're using Jackson Api for features like @JsonInclude(Include.NON_NULL) and @JsonPropertyOrder. 或者,创建一个新的Item Object并仅设置必需的属性,然后返回,假设您正在使用Jackson Api的@JsonInclude(Include.NON_NULL)和@JsonPropertyOrder之类的功能。

You can use marshalling your Item class to JSON in certain format. 您可以使用某些格式将Item类编组为JSON。 That will give u precisely what you want. 那会给你你想要的。 You will find out ways to do it in Spring Boot on google. 您将在Google的Spring Boot中找到实现此目的的方法。

If you don't wanna create an additional DTO class or have many different views- you can use Jackson @JsonView annotation on class fields. 如果您不想创建其他DTO类或具有许多不同的视图,则可以在类字段上使用Jackson @JsonView注释。 Example : 范例:

1)create class : 1)创建类:

public class View {
    public static class UI {}
    public static class NotUI {}
    public static class Rest {}
}

// you can create many different Views here; //您可以在此处创建许多不同的视图;

2) annotate needed fields of your entity; 2)注释您实体的必填字段;

    class Book{   
    String title;    
    String printType;
@JsonView(View.Rest.class) 
    Integer pageCount;

// pageCount have 'Rest' view and when controller have 'UI' view - pageCount will be missing // pageCount具有“ Rest”视图,而控制器具有“ UI”视图-pageCount将丢失

3)Annotate the controller method with appropriate context: 3)在适当的上下文中注释控制器方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM