Java JSON Conversion Tutorial

Java JSON Conversion Tutorial

This is a beginner level tutorial on using the Jackson JSON API to convert between Java objects and JSON data. We have been seeing a RESTful services tutorial series in the recent past. I will be using JSON conversion in RESTful services in the coming weeks. This JSON tutorial is to help started with it.

Java 9 features was announced earlier and it includes a JSON parser that is to be bundled with the java core lib. Once that is available, we may not need a third-party library. Till then, we have to go with an external library.

There are two options we can go with. First one is the popular Jackson JSON processor a third party API. Second one is the JSR 353, Java API for JSON Processing and its reference implementation JSON-P. In this tutorial, we will use the popular option, the Jackson JSON processor.

Jackson JSON Processing

Old jackson API was in codehaus.org and presently it is hosted at github and named as FasterXML/jackson. API’s package structure also changed tocom.fasterxml.jackson.*. Jackson Processor API library files can be downloaded from http://mvnrepository.com/artifact/com.fasterxml.jackson.core

Java to JSON Conversion

package com.javapapers.java;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaToJSON {
	public static void main(String[] args) {
		Animal crocodile = new Animal(1, "Crocodile", "Wild");
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			objectMapper.writeValue(new File("animal.json"), crocodile);
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			objectMapper.writerWithDefaultPrettyPrinter().writeValue(
					new File("prettyanimal.json"), crocodile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

JSON to Java Conversion

package com.javapapers.java;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONToJava {
	public static void main(String[] args) {
		Animal animal = null;
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			animal = objectMapper.readValue(new File("animal.json"),
					Animal.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(animal);
	}
}

Download Java to JSON to Java Example Project

JavaJsonConversion

JSON Conversion Output

animal.json

{"id":1,"firstName":"Crocodile","lastName":"Wild"}

prettyanimal.json

{
  "id" : 1,
  "firstName" : "Crocodile",
  "lastName" : "Wild"
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值