Jackson in Java for JSON
Jackson, https://github.com/FasterXML/jackson
Jackson has been known as "the Java JSON library" or "the best JSON parser for Java". Or simply as "JSON for Java".
Jackson version: 1.x: org.codehaus.jackson.xxx; 2.x: com.fastxml.jackson.xxx
To capitalize the first letter, you need the following:
1. Maven adds:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
2. Add to the attributes:
@JsonProperty( "Code")
3. Add to the Getter method:
@JsonIgnore
To implement toString()
#Ignore Case when converting JSON to beanimport com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import net.sf.json.JSONObject;@Override public String toString() { return JSONObject.fromObject(this).toString(); }public static void main(String[] args) throws JsonProcessingException { UserInfo userInfo = new UserInfo(); userInfo.setC_NAME("story"); System.out.println(new ObjectMapper().writeValueAsString(userInfo)); }
import com.fasterxml.jackson.annotation.JsonProperty;
public class DiagResponeBean {
@JsonProperty( "SN")
private String sn;
//setter/getter
}
//a part of controller codes
com.fasterxml.jackson.databind.ObjectMapper ob =new com.fasterxml.jackson.databind.ObjectMapper();
//Ignore Case when converting JSON to bean
ob.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
if(StringUtil.isEmpty(json)){
diagResponeBean.setSn("");
ob.writeValue(response.getOutputStream(), diagResponeBean);
return;
}
package com.jackson.json.databinding;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Country {
// Notes: bean's private properties need getter method, or change private to public
private String country_id;
private Date birthDate;
private List<String> nation = new ArrayList<String>();
private String[] lakes;
private List<Province> provinces = new ArrayList<Province>();
private Map<String, Integer> traffic = new HashMap<String, Integer>();
public Country() {
// TODO Auto-generated constructor stub
}
public Country(String countryId) {
this.country_id = countryId;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public List<String> getNation() {
return nation;
}
public void setNation(List<String> nation) {
this.nation = nation;
}
public String[] getLakes() {
return lakes;
}
public void setLakes(String[] lakes) {
this.lakes = lakes;
}
public Integer get(String key) {
return traffic.get(key);
}
public Map<String, Integer> getTraffic() {
return traffic;
}
public void setTraffic(Map<String, Integer> traffic) {
this.traffic = traffic;
}
public void addTraffic(String key, Integer value) {
traffic.put(key, value);
}
public List<Province> getProvinces() {
return provinces;
}
public void setProvinces(List<Province> provinces) {
this.provinces = provinces;
}
@Override
public String toString() {
return “Country [country_id=” + country_id + “, birthDate=” + birthDate
+ ”, nation=” + nation + “, lakes=” + Arrays.toString(lakes)
+ ”, province=” + provinces + “, traffic=” + traffic + “]”;
}
}
1) java object to json
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JavaBeanSerializeToJson {
public static void convert() throws Exception {
// ObjectMapper converts a java object to Json file
ObjectMapper mapper = new ObjectMapper();
// data format
SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd”);
mapper.setDateFormat(dateFormat);
Country country = new Country(“China”);
country.setBirthDate(dateFormat.parse(”1949-10-01”));
country.setLakes(new String[] { “Qinghai Lake”, “Poyang Lake”,
”Dongting Lake”, “Taihu Lake” });
List<String> nation = new ArrayList<String>();
nation.add(”Han”);
nation.add(”Meng”);
nation.add(”Hui”);
nation.add(”WeiWuEr”);
nation.add(”Zang”);
country.setNation(nation);
Province province = new Province();
province.name = ”Shanxi”;
province.population = 37751200;
Province province2 = new Province();
province2.name = ”ZheJiang”;
province2.population = 55080000;
List<Province> provinces = new ArrayList<Province>();
provinces.add(province);
provinces.add(province2);
country.setProvinces(provinces);
country.addTraffic(”Train(KM)”, 112000);
country.addTraffic(”HighWay(KM)”, 4240000);
// For showing, it is not for Product Envirement
//mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// avoid non empty properties
mapper.setSerializationInclusion(Include.NON_EMPTY);
// defalut Json's key name is Java property name, Jackson annotations can change Json key name.
mapper.writeValue(new File(“country.json”), country);
}
public static void main(String[] args) throws Exception {
convert();
}
}
2)json to java object
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Json to Java Object
*/
public class JsonDeserializeToJava {
public static void main(String[] args) throws Exception {
//ObjectMapper
ObjectMapper mapper = new ObjectMapper();
File json = new File(“country.json”);
//if json has 10 properties, the bean has 2 properties, others are avoid
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Country country = mapper.readValue(json, Country.class);
//System.out.println(”country_id:”+country.getCountry_id());
SimpleDateFormat dateformat = new SimpleDateFormat(“yyyy-MM-dd”);
String birthDate = dateformat.format(country.getBirthDate());
//System.out.println(”birthDate:”+birthDate);
List<Province> provinces = country.getProvinces();
for (Province province : provinces) {
//System.out.println(”province:”+province.name + “\n” + “population:”+province.population);
}
}
}
2.Tree Model handles Json
(1)tree model to json:
import java.io.File;
import java.io.FileWriter;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class SerializationExampleTreeModel {
public static void main(String[] args) throws Exception {
//1
JsonNodeFactory factory = new JsonNodeFactory(false);
//2
JsonFactory jsonFactory = new JsonFactory();
//3
JsonGenerator generator = jsonFactory.createGenerator(new FileWriter(new File(“country2.json”)));
ObjectMapper mapper = new ObjectMapper();
ObjectNode country = factory.objectNode();
country.put(”country_id”, “China”);
country.put(”birthDate”, “1949-10-01”);
//List and Array to json "obj:[]"
ArrayNode nation = factory.arrayNode();
nation.add(”Han”).add(“Meng”).add(“Hui”).add(“WeiWuEr”).add(“Zang”);
country.set(”nation”, nation);
ArrayNode lakes = factory.arrayNode();
lakes.add(”QingHai Lake”).add(“Poyang Lake”).add(“Dongting Lake”).add(“Taihu Lake”);
country.set(”lakes”, lakes);
ArrayNode provinces = factory.arrayNode();
ObjectNode province = factory.objectNode();
ObjectNode province2 = factory.objectNode();
province.put(”name”,“Shanxi”);
province.put(”population”, 37751200);
province2.put(”name”,“ZheJiang”);
province2.put(”population”, 55080000);
provinces.add(province).add(province2);
country.set(”provinces”, provinces);
ObjectNode traffic = factory.objectNode();
traffic.put(”HighWay(KM)”, 4240000);
traffic.put(”Train(KM)”, 112000);
country.set(”traffic”, traffic);
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.writeTree(generator, country);
}
}
(2) json to tree mode
DeserializationExampleTreeModel1.java, JsonNode type.
import java.io.File;
import java.util.Iterator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationExampleTreeModel1 {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// "JsonNode", ObjectMapper gets json's JsonNode as root
JsonNode node = mapper.readTree(new File(“country2.json”));
// print type of node
System.out.println(”node JsonNodeType:”+node.getNodeType());
// check if it is Container
System.out.println(”node is container Node ? ”+node.isContainerNode());
//
System.out.println(”———node's name————————-“);
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
System.out.print(fieldName+” ”);
}
System.out.println(”\n—————————————————–”);
// as.Text
JsonNode country_id = node.get(”country_id”);
System.out.println(”country_id:”+country_id.asText() + “ JsonNodeType:”+country_id.getNodeType());
JsonNode birthDate = node.get(”birthDate”);
System.out.println(”birthDate:”+birthDate.asText()+“ JsonNodeType:”+birthDate.getNodeType());
JsonNode nation = node.get(”nation”);
System.out.println(”nation:”+ nation+ “ JsonNodeType:”+nation.getNodeType());
JsonNode lakes = node.get(”lakes”);
System.out.println(”lakes:”+lakes+“ JsonNodeType:”+lakes.getNodeType());
JsonNode provinces = node.get(”provinces”);
System.out.println(”provinces JsonNodeType:”+provinces.getNodeType());
boolean flag = true;
for (JsonNode provinceElements : provinces) {
//avoid provinceElements multi prints,by flag checking,provinceElements are for JsonNodeType
if(flag){
System.out.println(”provinceElements JsonNodeType:”+provinceElements.getNodeType());
System.out.println(”provinceElements is container node? ”+provinceElements.isContainerNode());
flag = false;
}
Iterator<String> provinceElementFields = provinceElements.fieldNames();
while (provinceElementFields.hasNext()) {
String fieldName = (String) provinceElementFields.next();
String province;
if (“population”.equals(fieldName)) {
province = fieldName + ”:” + provinceElements.get(fieldName).asInt();
}else{
province = fieldName + ”:” + provinceElements.get(fieldName).asText();
}
System.out.println(province);
}
}
}
}
DeserializationExampleTreeModel2.java, JsonNode.path() ,path() likes DeserializationExampleTreeModel1.java get(),
// when node does not exist,get() return null, path() return MISSING type of JsonNode
package com.jackson.json.treemodel;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationExampleTreeModle2 {
public static void main(String[] args) throws JsonProcessingException, IOException{
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(new File(“country2.json”));
//when path() get JsonNode that does not exist,return MISSING type of JsonNode
JsonNode missingNode = node.path(”test”);
if(missingNode.isMissingNode()){
System.out.println(”JsonNodeType : ” + missingNode.getNodeType());
}
System.out.println(”country_id:”+node.path(“country_id”).asText());
JsonNode provinces = node.path(”provinces”);
for (JsonNode provinceElements : provinces) {
Iterator<String> provincesFields = provinceElements.fieldNames();
while (provincesFields.hasNext()) {
String fieldName = (String) provincesFields.next();
String province;
if(“name”.equals(fieldName)){
province = fieldName +”:”+ provinceElements.path(fieldName).asText();
}else{
province = fieldName +”:”+ provinceElements.path(fieldName).asInt();
}
System.out.println(province);
}
}
}
}
3.Stream handles Json
(1)stream to json
import java.io.File;
import java.io.FileWriter;
import java.io.Exception;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
public class StreamGeneratorJson {
public static void main(String[] args) throws Exception {
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(new FileWriter(new File(“country3.json”)));
generator.writeStartObject();
generator.writeFieldName(”country_id”);
generator.writeString(”China”);
generator.writeFieldName(”provinces”);
generator.writeStartArray();
generator.writeStartObject();
generator.writeStringField(”name”, “Shanxi”);
generator.writeNumberField(”population”, 33750000);
generator.writeEndObject();
generator.writeEndArray();
generator.writeEndObject();
generator.close();
}
}
(2)stream parse json
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class StreamParserJson {
public static void main(String[] args) throws JsonParseException,
IOException {
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(new File(“country3.json”));
while (!parser.isClosed()) {
// first token, token points json's first "{"
JsonToken token = parser.nextToken();
if (token == null) {
break;
}
// find "population" in country3.json when key is "provinces"
if (JsonToken.FIELD_NAME.equals(token)
&& ”provinces”.equals(parser.getCurrentName())) {
token = parser.nextToken();
if (!JsonToken.START_ARRAY.equals(token)) {
break;
}
// next "{"
token = parser.nextToken();
if (!JsonToken.START_OBJECT.equals(token)) {
break;
}
while (true) {
token = parser.nextToken();
if (token == null) {
break;
}
if (JsonToken.FIELD_NAME.equals(token)
&& ”population”.equals(parser.getCurrentName())) {
token = parser.nextToken();
System.out.println(parser.getCurrentName() + ” : ”
+ parser.getIntValue());
}
}
}
}
}
}
htt p : //w w w.c n blogs.com/lee0oo0/articles/2652528.html
htt p s://b l o g.c s d n. n e t/xiong9999/article/details/53781695
end;
评论
发表评论