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

How to Convert Java Objects to JSON using Jackson?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 07:15:11451browse

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>
  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);
}

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"
    }]
}

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!

Statement:
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