Home > Java > javaTutorial > How to Convert Java Objects to JSON using Jackson?

How to Convert Java Objects to JSON using Jackson?

Patricia Arquette
Release: 2024-11-26 07:15:11
Original
433 people have browsed it

How to Convert Java Objects to JSON using Jackson?

Converting Java Objects to JSON Using Jackson

Object Structure

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.

Object Mapping and JSON Conversion

To convert the ValueData object to JSON, you need to use the Jackson library:

  1. Add the following dependency to your project's pom.xml:
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.13.3</version>
</dependency>
Copy after login
  1. In your main method, use Jackson to convert the object:
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);
}
Copy after login

JSON Output

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"
    }]
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template