原文地址:

Create JSON by Jackson API

Jackson API is a multi-purpose Java library for processing JSON. Using Jackson API we can process as well produce JSON in different ways. In this article we will show how to use this Jackson API for creating JSON.

Maven Dependency:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>

Example 1:Jackson API to create JSON Array

package com.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; public class CreateJSON { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); /**
* Create three JSON Objects objectNode1, objectNode2, objectNode3
* Add all these three objects in the array
*/ ObjectNode objectNode1 = mapper.createObjectNode();
objectNode1.put("bookName", "Java");
objectNode1.put("price", "100"); ObjectNode objectNode2 = mapper.createObjectNode();
objectNode2.put("bookName", "Spring");
objectNode2.put("price", "200"); ObjectNode objectNode3 = mapper.createObjectNode();
objectNode3.put("bookName", "Liferay");
objectNode3.put("price", "500"); /**
* Array contains JSON Objects
*/
arrayNode.add(objectNode1);
arrayNode.add(objectNode2);
arrayNode.add(objectNode3); /**
* We can directly write the JSON in the console.
* But it wont be pretty JSON String
*/
System.out.println(arrayNode.toString()); /**
* To make the JSON String pretty use the below code
*/
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode)); } }

The above code will produce the below JSON

[
{
"bookName": "Java",
"price": "100"
},
{
"bookName": "Spring",
"price": "200"
},
{
"bookName": "Liferay",
"price": "500"
}
]

Example 2: Jackson API to create JSON Array inside JSON Array

package com.sample;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; public class CreateJSON { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); /**
* Create three JSON Objects objectNode1, objectNode2, objectNode3, objectNode4
* Add all these three objects in the array
*/ ObjectNode objectNode1 = mapper.createObjectNode();
objectNode1.put("bookName", "Java");
objectNode1.put("price", "100"); ObjectNode objectNode2 = mapper.createObjectNode();
objectNode2.put("bookName", "Spring");
objectNode2.put("price", "200"); ObjectNode objectNode3 = mapper.createObjectNode();
objectNode3.put("bookName", "Liferay");
objectNode3.put("price", "500"); ArrayNode authorsArray = mapper.createArrayNode();
ObjectNode author1 = mapper.createObjectNode();
author1.put("firstName","Hamidul");
author1.put("middleName","");
author1.put("lastName","Islam"); ObjectNode author2 = mapper.createObjectNode();
author2.put("firstName","Richard");
author2.put("middleName","");
author2.put("lastName","Sezove"); authorsArray.add(author1);
authorsArray.add(author2); ObjectNode objectNode4 = mapper.createObjectNode();
objectNode4.putPOJO("authors", authorsArray); /**
* Array contains JSON Objects
*/
arrayNode.add(objectNode1);
arrayNode.add(objectNode2);
arrayNode.add(objectNode3);
arrayNode.add(objectNode4); /**
* We can directly write the JSON in the console.
* But it wont be pretty JSON String
*/
//System.out.println(arrayNode.toString()); /**
* To make the JSON String pretty use the below code
*/
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode)); } }

The above code will produce the below JSON String

[
{
"bookName": "Java",
"price": "100"
},
{
"bookName": "Spring",
"price": "200"
},
{
"bookName": "Liferay",
"price": "500"
},
{
"authors": [
{
"firstName": "Hamidul",
"middleName": "",
"lastName": "Islam"
},
{
"firstName": "Richard",
"middleName": "",
"lastName": "Sezove"
}
]
}
]

Example 3: Jackson API to convert Java Object to JSON

package com.sample.pojo;

import java.util.List;

public class Customer {
private String firstName;
private String middleName;
private String lastName;
private int age;
private List<String> contacts; public List<String> getContacts() {
return contacts;
} public void setContacts(List<String> contacts) {
this.contacts = contacts;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getMiddleName() {
return middleName;
} public void setMiddleName(String middleName) {
this.middleName = middleName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }

Convert Customer to JSON

package com.sample;

import java.io.File;
import java.io.IOException;
import java.util.Arrays; import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.pojo.Customer; public class ObjectToJSON { public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
/**
* Mapper can be used to convert object to JSON
*/
ObjectMapper mapper = new ObjectMapper(); Customer customer = new Customer();
customer.setAge(29);
customer.setFirstName("Hamidul");
customer.setMiddleName("");
customer.setLastName("Islam");
customer.setContacts( Arrays.asList("8095185442", "9998887654", "1234567890")); /**
* Now we can create JSON from customer object
* Into different forms
* We can write in Console or we can create JSON as string
* Or we can write JSON in file also
* See all the examples below
*/ mapper.writeValue(System.out, customer); String jsonString = mapper.writeValueAsString(customer); mapper.writeValue(new File("customer.json"), customer); /**
* To pretty print the above JSON use the below code.
* Uncomment the below code to see the result
*/ /**mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, customer); String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(customer); mapper.writerWithDefaultPrettyPrinter().writeValue(new File("customer.json"), customer);*/
} }

The above code will produce JSON as below

{
"firstName": "Hamidul",
"middleName": "",
"lastName": "Islam",
"age": 29,
"contacts": [
"8095185442",
"9998887654",
"1234567890"
]
}

Example 4: Use of @JsonIgnore to ignore property

Some times while converting java objects to json we may require certain properties to be ignored.

In that case we can use @JsonIgnore annotation. For example

package com.sample.pojo;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class Customer {
private String firstName;
private String middleName;
private String lastName;
private int age;
private List<String> contacts; @JsonIgnore
private String country; @JsonIgnore
private String city; public String getCountry() {
return country;
} public void setCountry(String country) {
this.country = country;
} public String getCity() {
return city;
} public void setCity(String city) {
this.city = city;
} public List<String> getContacts() {
return contacts;
} public void setContacts(List<String> contacts) {
this.contacts = contacts;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getMiddleName() {
return middleName;
} public void setMiddleName(String middleName) {
this.middleName = middleName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} }

So while converting customer object to JSON, the property country and city will be ignored. 

Example 5: Ignore property in the runtime

 

In the example 4 we have shown how to ignore property by @JsonIgnore. This is static in nature. That means each and every time the property will be ignored while converting object to JSON. But in some cases we may need to ignore property in the runtime on the basis of some conditions.

package com.sample.pojo;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonFilter;

@JsonFilter("com.sample.pojo.Customer")
public class Customer {
private String firstName;
private String middleName;
private String lastName;
private int age;
private List<String> contacts;
private String country;
private String city; public List<String> getContacts() {
return contacts;
} public void setContacts(List<String> contacts) {
this.contacts = contacts;
} public String getCountry() {
return country;
} public void setCountry(String country) {
this.country = country;
} public String getCity() {
return city;
} public void setCity(String city) {
this.city = city;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getMiddleName() {
return middleName;
} public void setMiddleName(String middleName) {
this.middleName = middleName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Customer(String firstName, String middleName, String lastName,
int age) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
} public Customer() { } }

Note: Give attention to @JsonFilter("com.sample.pojo.Customer"). Within double quote we can pass any valid string.

package com.sample;

import java.util.Arrays;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.sample.pojo.Customer; public class DynamicExclusionDemo { public static void main(String[] args) throws JsonProcessingException{ /**
* Create customer object
*/ Customer customer = new Customer();
customer.setAge(29);
customer.setFirstName("Hamidul");
customer.setMiddleName("");
customer.setLastName("Islam");
customer.setCountry("India");
customer.setCity("Bangalore");
customer.setContacts( Arrays.asList("8095185442", "9998887654", "1234567890")); /**
* Ignore city and country property
*/
String[] ignorableFieldNames = {"city","country"}; /**
* In the add filter pass com.sample.pojo.Customer
* Which is mentioned in the Customer class with @JsonFilter
*/
FilterProvider filters = new SimpleFilterProvider() .addFilter("com.sample.pojo.Customer", SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames)); ObjectMapper mapper = new ObjectMapper(); /**
* Pass the filter
*/
ObjectWriter writer = mapper.writer(filters); /**
* Convert Object to JSON
*/
String jsonString = writer.writeValueAsString(customer);
System.out.println(jsonString); }
}

The JSON output is below

Create JSON by Jackson API(转)的更多相关文章

  1. URL及日期等特殊数据格式处理-JSON框架Jackson精解第2篇

    Jackson是Spring Boot默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的,没有这种限制.它提供了很 ...

  2. 两款JSON类库Jackson与JSON-lib的性能对比(新增第三款测试)

    本篇文章主要介绍了"两款JSON类库Jackson与JSON-lib的性能对比(新增第三款测试)",主要涉及到两款JSON类库Jackson与JSON-lib的性能对比(新增第三款 ...

  3. 属性序列化自定义与字母表排序-JSON框架Jackson精解第3篇

    Jackson是Spring Boot默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的,没有这种限制.它提供了很 ...

  4. @JsonCreator自定义反序列化函数-JSON框架Jackson精解第5篇

    Jackson是Spring Boot(SpringBoot)默认的JSON数据处理框架,但是其并不依赖于任何的Spring 库.有的小伙伴以为Jackson只能在Spring框架内使用,其实不是的, ...

  5. 使用 Json Schema 定义 API

    本文地址:使用 Json Schema 定义 API 前面我们介绍了 Json Schema 的基本内容,这篇文章我们结合 jsonschema2pojo 工具深入分析如何使用 Json Schema ...

  6. RandomUser – 生成随机用户 JSON 数据的 API

    RandomUser 是一个 API,它为您提供了一个或者一批随机生成的用户.这些用户可以在 Web 应用程序原型中用作占位符,将节省您创建自己的占位符信息的时间.您可以使用 AJAX 或其他方法来调 ...

  7. Json for Java API学习

    首先声明:本文来个非常多网友的博客,我通过參考了他们的博客,大致的了解了一些项目中经常使用的Json in java 类和方法,以及关于json的个人理解 个人对json的一些简单理解 在近期的学习中 ...

  8. json模块及其API

    模块:json 所包含API列表: json.dumps : 将python对象转换成json格式 json.loads : 将json格式字符串转换为python对象 ——————————————— ...

  9. [py]requests+json模块处理api数据,flask前台展示

    需要处理接口json数据,过滤字段,处理字段等. 一大波json数据来了 参考: https://stedolan.github.io/jq/tutorial/ https://api.github. ...

随机推荐

  1. DPDK 网卡绑定和解绑

    参考: DPDK网卡绑定和解绑 DPDK的安装与绑定网卡 DPDK 网卡绑定和解绑 注意: 建议不要使用本文的eth0网卡绑定dpdk驱动. 1.进入DPDK目录: $ cd dpdk/tools/ ...

  2. FPGA 概述2

    参考1 参考2:浅论各种调试接口(SWD.JTAG.Jlink.Ulink.STlink)的区别 以下数据仅供参考 文章概要 主流FPGA厂商及产品 相同设计在FPGA与ASIC中耗费器件数量比较 F ...

  3. StringBuilder的三种删除方法比较

    分别用一千万次循环来比较StringBuilder的三种删除方法所用时间 未避免偶然性,再循环一百次来比较总时间 --主类 public class StringBuilderRemove { pub ...

  4. python学习 day02打卡

    今天主要学习的内容: 1.while 循环 :  语法: while 条件 : 循环体 #判断条件是否成立.如果成立执行循环体.然后再次判断条件...直到条件不成立石跳出循环 else : 当条件不成 ...

  5. Mybatis工程搭建

    工程搭建 • 1依赖包 • 2配置文件 • 2.1spring-mybatis.xml • 2.2mybatis-config.xml自带配置文件 • 2.3 mapper(dao)对象 • 2.4 ...

  6. P1182 数列分段`Section II`

    传送门 思路: 求数列每段和的最大值的最小值,很明显是用二分法求解,加贪心检验.本题关键是要怎么去高效的check,可以考虑一个贪心的思路,能加的就加上,不能则新开一段,so对于二分的值 u ,我们从 ...

  7. hibernate框架入门配置

    1.新建一个项目(可以是java项目,也可以是webapp) 2.导入jar包,包括日志,mysql驱动,必备request包,jpa配置规范包 3.创建实体类 1.创建数据库,使用hibernate ...

  8. 力扣(LeetCode)976. 三角形的最大周长

    给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的.面积不为零的三角形的最大周长. 如果不能形成任何面积不为零的三角形,返回 0. 示例 1: 输入:[2,1,2] 输出:5 示例 2 ...

  9. 加速cin的技巧

     ios::sync_with_stdio(false); cin.tie(0);  把cin变得和scanf一样快.

  10. Python Scrapy 爬取煎蛋网妹子图实例(二)

    上篇已经介绍了 图片的爬取,后来觉得不太好,每次爬取的图片 都在一个文件下,不方便区分,且数据库中没有爬取的时间标识,不方便后续查看 数据时何时爬取的,所以这里进行了局部修改 修改一:修改爬虫执行方式 ...