Convert Javabean objects to Json objects using Jackson

1. Brief description of json 
json is a lightweight data exchange format, which adopts a completely independent text language format, which is very suitable for the interaction between web servers and JavaScript.
Its characteristics make it an ideal data exchange language, so it makes Very popular in web applications.

2. Use jackson framework to process Json
jackson is a tool for processing POJO and JavaBean objects. It can easily convert Java objects into json objects, and the performance
is far better than other json frameworks such as json-lib, Gson, etc. Need high-

demand jar package: From jackson's official website, you can see that the latest version is 2.0, and we only use the
download address of version 1.x during the insurance period: http://jackson.codehaus.org/1.7.6/jackson- all-1.7.6.jar

requirements: The user inputs parameters from the View and passes them to the background. After data processing in the background, the processed results need to be returned to the client in the format of Json
(for example: when the user logs in, enter the user name and password) , After the background data processing, all the user's information is stored in the JavaBean.
What Jackson has to do is to convert the JavaBean object into a Json object.)

First establish the data model JavaBean

public class User implements Serializable{

private int id;
private String name;
private String password;
private String telephone;

setXXX;

getXXX;
}

利用org.codehaus.jackson.map.ObjectMapper

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJackson {

private ObjectMapper mapper = null;

public TestJackson() {
mapper = new ObjectMapper();
}

public String PojoToJson(Object obj) {
StringWriter sw = new StringWriter();
try {
mapper.writeValue(sw, obj);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

if(sw != null) {
try {
sw.flush();
sw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return sw.toString();

}

@SuppressWarnings("unchecked")
public static void main(String[] args) {
TestJackson test = new TestJackson();

User user = new User();

user.setId(1);
user.setName("name");
user.setPassword("password");
user.setTelephone("1234565");

List list = new ArrayList();
list.add(1);
list.add(12);
list.add(123);
list.add(123);

Map map = new HashMap();
Map map1 = new HashMap();
map1.put("city", "bejing");
map1.put("district", "tianjin");

map.put("name", "foreveross");
map.put("address", map1);


System.out.println(test.PojoToJson(user));
System.out.println(test.PojoToJson(list));
System.out.println(test.PojoToJson(map));

}

}

结果:

{"id":1,"name":"name","password":"password","telephone":"1234565"}
[1,12,123,123]
{"address":{"district":"tianjin","city":"bejing"},"name":"foreveross"} any Java value as output in Json format

This method mainly uses the mapper.writeValue method, which uses the provided output stream and can serialize


利用org.codehaus.jackson.map.ObjectMapper

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestJackson {

private JsonGenerator jsonGenerator = null;

private ObjectMapper objectMapper = null;

private OutputStream os = System.out;

public TestJackson() {
objectMapper = new ObjectMapper();

try {

jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
os, JsonEncoding.UTF8);

} catch (IOException e) {

e.printStackTrace();
}

}

public String PojoToJson(Object obj) {

try {
jsonGenerator.writeObject(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return os.toString().substring(0,
os.toString().lastIndexOf("java.io.PrintStream"));
}

public void close() {

try {

if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}

if (os != null) {
os.close();
}

} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Test2 t = new Test2();
User user = new User();

user.setId(1);
user.setName("name");
user.setPassword("password");
user.setTelephone("1234565");

Map<String, Object> userData = new HashMap<String, Object>();
Map<String, String> nameStruct = new HashMap<String, String>();
nameStruct.put("first", "Joe");
nameStruct.put("last", "Sixpack");
userData.put("name", nameStruct);
userData.put("gender", "MALE");
userData.put("verified", Boolean.FALSE);
userData.put("userImage", "Rm9vYmFyIQ==");

System.out.println(t.PojoToJson(userData));
System.out.println(t.PojoToJson(user));
t.close();

}

}

The above uses the writeValue method of ObjectMapper and the writeObject method of JsonGenerator to complete the matching The conversion of Java objects,
the parameters passed and the way of construction are different; the creation of JsonGenerator depends on the ObjectMapper object. That is if you want to use JsonGenerator to convert JSON.
Then you must create an ObjectMapper. But if you use ObjectMapper to convert JSON, you don't need JSONGenerator.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327000997&siteId=291194637