您的位置:首页 > 编程语言 > Java开发

Java JSON Conversion Tutorial

2016-12-02 00:51 246 查看


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 to
com.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"
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: