java's Jackson framework enables easy conversion of JSON
- 2020-06-03 06:32:53
- OfStack
Jackson can easily convert Java objects to json objects and xml documents, as well as json and xml to Java objects.
Jackson relies on fewer jar packages than the ES10en-ES11en framework, is simple to use and has relatively high performance. Moreover, the Jackson community is relatively active and updated quickly.
1. Preparation
1. Download the jar package
The Jackson jar all download address: http: / / jackson codehaus. org 1.7.6 / jackson - all - 1.7.6. jar
You can then import the jar package into your project and get started
Example: official http: / / wiki fasterxml. com/JacksonInFiveMinutes
Since the following program is running with the junit test case, the jar package for junit has to be added. Version is junit - 4.2.8
If you need to convert xml, you also need stax2-ES52en.jar
2. The basic code of test class is as follows
package com.hoo.test;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.xml.XmlMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.AccountBean;
/**
* <b>function:</b>Jackson will java Object conversion to JSON String, you can also put JSON String conversion to java object
* jar-lib-version: jackson-all-1.6.2
* jettison-1.0.1
* @author hoojo
* @file JacksonTest.java
* @package com.hoo.test
* @project Spring3
* @version 1.0
*/
@SuppressWarnings("unchecked")
public class JacksonTest {
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private AccountBean bean = null;
@Before
public void init() {
bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("hoojo_@126.com");
bean.setId(1);
bean.setName("hoojo");
objectMapper = new ObjectMapper();
try {
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void destory() {
try {
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
jsonGenerator = null;
objectMapper = null;
bean = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. JavaEntity required
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
Birthday
package com.hoo.entity;
public class Birthday {
private String birthday;
public Birthday(String birthday) {
super();
this.birthday = birthday;
}
//getter , setter
public Birthday() {}
@Override
public String toString() {
return this.birthday;
}
}
2. Java object converted to JSON
1, JavaBean(Entity/Model) converted to JSON
/**
* function: will java Object conversion to json string
* @author hoojo
*/
@Test
public void writeEntityJSON() {
try {
System.out.println("jsonGenerator");
//writeObject Can convert java Object, eg:JavaBean/Map/List/Array Etc.
jsonGenerator.writeObject(bean);
System.out.println();
System.out.println("ObjectMapper");
//writeValue With and writeObject Same function
objectMapper.writeValue(System.out, bean);
} catch (IOException e) {
e.printStackTrace();
}
}
The results after operation are as follows:
jsonGenerator
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}
ObjectMapper
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":hoojo_@126.com}
Above, JsonGenerator's writeObject method and ObjectMapper's writeValue method are respectively used to complete the transformation of Java object. The parameters passed by the two methods and their construction methods are different. The creation of JsonGenerator depends on the ObjectMapper object. This means that if you want to use JsonGenerator to convert JSON, you must create an ObjectMapper. But if you use ObjectMapper to convert JSON, you do not need JSONGenerator.
The writeValue method of objectMapper converts an Java object to JSON. Parameter 1 of this method needs to provide an output stream through which the transformed content can be output. Or provide an File to write the converted to File. Of course, this parameter can also receive 1 JSONGenerator and then output the converted information via JSONGenerator. The second parameter is the Java object to be transformed. If you use a three-parameter method, it is 1 Config. This config can provide some conversion rules, filtering or conversion over some properties of the specified Java object.
2. Convert Map set to Json string
/**
* <b>function:</b> will map Converted to json string
* @author hoojo
*/
@Test
public void writeMapJSON() {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", bean.getName());
map.put("account", bean);
bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("hoojo@qq.com");
map.put("account2", bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
The results after conversion are as follows:
jsonGenerator
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"}}
objectMapper
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"hoojo@qq.com"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":hoojo_@126.com}}
3. Convert List set to json
/**
* <b>function:</b> will list Set conversion to json string
* @author hoojo
*/
@Test
public void writeListJSON() {
try {
List<AccountBean> list = new ArrayList<AccountBean>();
list.add(bean);
bean = new AccountBean();
bean.setId(2);
bean.setAddress("address2");
bean.setEmail("email2");
bean.setName("haha2");
list.add(bean);
System.out.println("jsonGenerator");
//list Converted to JSON string
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("ObjectMapper");
// with objectMapper Direct return list Into the JSON string
System.out.println("1###" + objectMapper.writeValueAsString(list));
System.out.print("2###");
//objectMapper list Converted to JSON string
objectMapper.writeValue(System.out, list);
} catch (IOException e) {
e.printStackTrace();
}
}
The results are as follows:
jsonGenerator
[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
ObjectMapper
1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
There's an extra [] bracket around it; Similarly, Array can be converted. The conversion of JSON is the same as the above result, so there is no conversion here. ~. ~
4. Let's take a look at some of the types provided by jackson and use them to perform json conversion. If you use these JSON conversions, you can perform complex JSON conversions without JavaBean(Entity). These types are used to build a complex Java object and complete the JSON transformation.
@Test
public void writeOthersJSON() {
try {
String[] arr = { "a", "b", "c" };
System.out.println("jsonGenerator");
String str = "hello world jackson!";
//byte
jsonGenerator.writeBinary(str.getBytes());
//boolean
jsonGenerator.writeBoolean(true);
//null
jsonGenerator.writeNull();
//float
jsonGenerator.writeNumber(2.2f);
//char
jsonGenerator.writeRaw("c");
//String
jsonGenerator.writeRaw(str, 5, 10);
//String
jsonGenerator.writeRawValue(str, 5, 5);
//String
jsonGenerator.writeString(str);
jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
System.out.println();
//Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectFieldStart("user");//user:{
jsonGenerator.writeStringField("name", "jackson");//name:jackson
jsonGenerator.writeBooleanField("sex", true);//sex:true
jsonGenerator.writeNumberField("age", 22);//age:22
jsonGenerator.writeEndObject();//}
jsonGenerator.writeArrayFieldStart("infos");//infos:[
jsonGenerator.writeNumber(22);//22
jsonGenerator.writeString("this is array");//this is array
jsonGenerator.writeEndArray();//]
jsonGenerator.writeEndObject();//}
AccountBean bean = new AccountBean();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
//complex Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectField("user", bean);//user:{bean}
jsonGenerator.writeObjectField("infos", arr);//infos:[array]
jsonGenerator.writeEndObject();//}
} catch (Exception e) {
e.printStackTrace();
}
}
After running, the results are as follows:
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
0
How's that? The json string is constructed and the output is 1. The key is to understand the method provided by JSONGenerator and complete the construction of 1 Object.
3. JSON converted to Java object
1. Convert json string to JavaBean object
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
1
Quite simply, the method readValue, which USES the object ObjectMapper, needs to provide two parameters. The first argument is the parsed JSON string, and the second argument is the type of Java object that will be parsed by the JSON. Of course, there are other ways to sign the same thing, and if you're interested, 11 try using the same method, which is of course very similar to the one you're currently using. After running, the results are as follows:
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
2
2. Convert json string to List < Map > A collection of
/**
* <b>function:</b>json String conversion to list<map>
* @author hoojo
*/
@Test
public void readJson2List() {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
"{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
try {
List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
Map<String, Object> map = list.get(i);
Set<String> set = map.keySet();
for (Iterator<String> it = set.iterator();it.hasNext();) {
String key = it.next();
System.out.println(key + ":" + map.get(key));
}
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
An attempt was made to convert the above JSON to List and then store AccountBean in List, but failed. However, the Map collection is supported. Because you convert to ES181en.class, but don't know what type of List is stored. I had no choice but to remain silent. Because all objects can be converted to Map, the result is as follows:
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
4
3, Json string converted to Array array, because the above generic cast cannot identify the object type in the collection. So we're going to use an array of objects here to solve this problem. But instead of a set, it's an array. Of course this doesn't matter, you can convert it to List using Arrays.asList.
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
5
Results after operation:
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
6
4. Json string converted to Map collection
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
7
The results after operation are as follows:
3
success:true
A:{address=address2, name=haha2, id=2, email=email2}
B:{address=address, name=haha, id=1, email=email}
4. Jackson's support for XML
Jackson can also convert the java object to xml. The result is more intuitive than json-ES216en, but it relies on the stax2-ES218en.jar package.
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter , setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
9
Run the above method and the results are as follows:
XmlMapper
<unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown>
<unknown><unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></unknown>
<email><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></email></unknown>
<unknown><A><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></A>
<B><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>hoojo_@126.com</email></B></unknown>
As a result, the problem that the root nodes are all unknown has not been solved. Since the root node has not been converted, the parsing of xml to Java objects cannot be completed.