View Javadoc
1   /*
2    * Copyright 2019-2023 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.demo;
6   
7   import com.fasterxml.jackson.core.JsonProcessingException;
8   import com.fasterxml.jackson.databind.ObjectMapper;
9   
10  import oshi.SystemInfo;
11  import oshi.annotation.SuppressForbidden;
12  import oshi.hardware.CentralProcessor;
13  import oshi.hardware.GlobalMemory;
14  import oshi.hardware.HardwareAbstractionLayer;
15  
16  /**
17   * Demonstrates the use of Jackson's ObjectMapper to create JSON from OSHI objects
18   */
19  public class Json {
20      /**
21       * <p>
22       * main.
23       * </p>
24       *
25       * @param args an array of {@link java.lang.String} objects.
26       */
27      @SuppressForbidden(reason = "Using System.out in a demo class")
28      public static void main(String[] args) {
29          // Jackson ObjectMapper
30          ObjectMapper mapper = new ObjectMapper();
31  
32          // Fetch some OSHI objects
33          SystemInfo si = new SystemInfo();
34          HardwareAbstractionLayer hal = si.getHardware();
35  
36          try {
37              // Pretty print computer system
38              System.out.println("JSON for CPU:");
39              CentralProcessor cpu = hal.getProcessor();
40              System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cpu));
41  
42              // Print memory
43              System.out.println("JSON for Memory:");
44              GlobalMemory mem = hal.getMemory();
45              System.out.println(mapper.writeValueAsString(mem));
46  
47          } catch (JsonProcessingException e) {
48              System.out.println("Exception encountered: " + e.getMessage());
49          }
50      }
51  }