To achieve your desired JSON output, your classes are structured correctly. ValueData represents the main object containing a list of ValueItems. Each ValueItems object represents an entry in the information array.
To convert the ValueData object to JSON, you need to use the Jackson library:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency>
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; public static void main(String[] args) throws Exception { // Create Java object ValueData valueData = ... ; // Create and initialize the ValueData object ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(valueData); System.out.println(json); }
The writeValueAsString method generates the JSON string in the desired format:
{ "information": [{ "timestamp": "xxxx", "feature": "xxxx", "ean": 1234, "data": "xxxx" }, { "timestamp": "yyy", "feature": "yyy", "ean": 12345, "data": "yyy" }] }
This output matches the desired JSON format specified in your question.
The above is the detailed content of How to Convert Java Objects to JSON using Jackson?. For more information, please follow other related articles on the PHP Chinese website!