0

I have this code,

        ClassPathResource classPathResource = new ClassPathResource("json/data.json");
        try {
            byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            strJson = new String(binaryData, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

         System.out.println(strJson); //works fine here
         return strJson;  //return it doesn't display pretty on browser

Any idea how to fix this? I've been trying all the solution here on the internet and especially stackoverflow and none of it works.

If you want clear view, it's from my previous code

Ricky Vene
  • 105
  • 1
  • 11

1 Answers1

0

I use thymeleaf html again,

@Controller
@RequestMapping("/menu")
public class DataController {

    // load json

    private List<DataModel> theDatawiz;
    private String strJson = null;

    @PostConstruct
    private void loadData() {
        // load json
        
        ClassPathResource classPathResource = new ClassPathResource("json/data.json");
        try {
            byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            strJson = new String(binaryData, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // setup array mapper
        ObjectMapper objectMapper = new ObjectMapper();
        DataModel[] datawiz = null;
        try {
            datawiz = objectMapper.readValue(strJson, DataModel[].class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // create the list
        theDatawiz = new ArrayList<>();

        for(int i = 0; i < datawiz.length; i++) {
            DataModel dat = new DataModel(datawiz[i].getId(),datawiz[i].getName());
            theDatawiz.add(dat);
        }

    }

    // add mapping for "/list"
    @GetMapping("/list")
    public String listMenu(Model theModel) {

        // add to the spring model
        theModel.addAttribute("thelist", theDatawiz);

        return "menu-list";
    }
    
    // add mapping for "/list"
    @GetMapping("/jason")
    public String printJson(Model theModel) {

        // add to the spring model
        theModel.addAttribute("result", strJson);

        return "jason";
    }   
}

On the jason.html,

<p th:text="'JSON: ' + ${result}"  style="white-space: pre"></p>    
Ricky Vene
  • 105
  • 1
  • 11