如何将User Bean的可选列表传递给JsonParser以生成PDF

我正在尝试从Spring引导应用程序生成PDF。我正在使用itextpdf和pdfbox。我正在Optional<List<User>> bean中获取所需的用户详细信息。如何将这个bean转换/传递给仅接受字符串的JsonParser?

这是我到目前为止尝试过的

控制器:-

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM;
import static javax.ws.rs.core.Response.status;
import static org.apache.http.HttpStatus.SC_BAD_REQUEST;
import static org.apache.http.HttpStatus.SC_OK;

@Slf4j
@EnableLogging
@Path("/UserDetails")
public class UserDetails {

    @GET
    @Produces(APPLICATION_JSON)
    public Response execute() throws WebApplicationException,FileNotFoundException,DocumentException {

        Optional<List<User>> user = DAO.getUsers();



        if (user.isPresent()) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse("Some String");
            String prettyJsonString = gson.toJson(je);
            Document document = new Document();
            PdfWriter.getInstance(document,new FileOutputStream("myJSON.pdf"));

            document.open();
            Font font = FontFactory.getFont(FontFactory.COURIER,16,BaseColor.BLACK);
            Chunk chunk = new Chunk(prettyJsonString,font);

            document.add(chunk);
            document.close();
            return status(SC_OK).entity(user).build();
        } else {
            return status(SC_BAD_REQUEST).entity(user).build();
        }
    }
}
CURRY8888 回答:如何将User Bean的可选列表传递给JsonParser以生成PDF

首先,您需要将Java对象转换为JSON字符串,您可以通过以下方式做到这一点:

Gson gson = new Gson();
String jsonInString = gson.toJson(yourObj);

请记住,gson对于在序列化过程中如何格式化输出有很多选择。

本文链接:https://www.f2er.com/3118131.html

大家都在问