程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java的Jackson框架完成隨便轉換JSON

java的Jackson框架完成隨便轉換JSON

編輯:關於JAVA

java的Jackson框架完成隨便轉換JSON。本站提示廣大學習愛好者:(java的Jackson框架完成隨便轉換JSON)文章只能為提供參考,不一定能成為您想要的結果。以下是java的Jackson框架完成隨便轉換JSON正文


Jackson可以輕松的將Java對象轉換成json對象和xml文檔,異樣也可以將json、xml轉換成Java對象。

相比json-lib框架,Jackson所依賴的jar包較少,復雜易用並且功能也要絕對高些。而且Jackson社區絕對比擬活潑,更新速度也比擬快。

一、預備任務

1、 下載依賴庫jar包

Jackson的jar all下載地址:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

然後在工程中導入這個jar包即可開端任務

官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

由於上面的順序是用junit測試用例運轉的,所以還得添加junit的jar包。版本是junit-4.2.8

假如你需求轉換xml,那麼還需求stax2-api.jar

2、 測試類根本代碼如下

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 將java對象轉換成JSON字符串,也可以將JSON字符串轉換成java對象
 * 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("[email protected]");
    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

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;
  }
}

二、Java對象轉換成JSON

1、 JavaBean(Entity/Model)轉換成JSON

/**
 * function:將java對象轉換成json字符串
 * @author hoojo
 */
@Test
public void writeEntityJSON() {
  
  try {
    System.out.println("jsonGenerator");
    //writeObject可以轉換java對象,eg:JavaBean/Map/List/Array等
    jsonGenerator.writeObject(bean);  
    System.out.println();
    
    System.out.println("ObjectMapper");
    //writeValue具有和writeObject相反的功用
    objectMapper.writeValue(System.out, bean);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

運轉後後果如下:

jsonGenerator
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"}
ObjectMapper
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":[email protected]}

下面辨別應用JsonGenerator的writeObject辦法和ObjectMapper的writeValue辦法完成對Java對象的轉換,二者傳遞的參數及結構的方式不同;JsonGenerator的創立依賴於ObjectMapper對象。也就是說假如你要運用JsonGenerator來轉換JSON,那麼你必需創立一個ObjectMapper。但是你用ObjectMapper來轉換JSON,則不需求JSONGenerator。

objectMapper的writeValue辦法可以將一個Java對象轉換成JSON。這個辦法的參數一,需求提供一個輸入流,轉換後可以經過這個流來輸入轉換後的內容。或是提供一個File,將轉換後的內容寫入到File中。當然,這個參數也可以接納一個JSONGenerator,然後經過JSONGenerator來輸入轉換後的信息。第二個參數是將要被轉換的Java對象。假如用三個參數的辦法,那麼是一個Config。這個config可以提供一些轉換時的規則,過指定的Java對象的某些屬性停止過濾或轉換等。

2、 將Map集合轉換成Json字符串

/**
 * <b>function:</b>將map轉換成json字符串
 * @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("[email protected]");
    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();
  }
}

轉換後後果如下:

jsonGenerator
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"[email protected]"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"}}
objectMapper
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"[email protected]"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":[email protected]}}

3、 將List集合轉換成json

/**
 * <b>function:</b>將list集合轉換成json字符串
 * @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轉換成JSON字符串
    jsonGenerator.writeObject(list);
    System.out.println();
    System.out.println("ObjectMapper");
    //用objectMapper直接前往list轉換成的JSON字符串
    System.out.println("1###" + objectMapper.writeValueAsString(list));
    System.out.print("2###");
    //objectMapper list轉換成JSON字符串
    objectMapper.writeValue(System.out, list);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

後果如下:

jsonGenerator
[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
ObjectMapper
1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]

裡面就是多了個[]中括號;異樣Array也可以轉換,轉換的JSON和下面的後果是一樣的,這裡就不再轉換了。~.~

4、上面來看看jackson提供的一些類型,用這些類型完成json轉換;假如你運用這些類型轉換JSON的話,那麼你即便沒有JavaBean(Entity)也可以完成復雜的Java類型的JSON轉換。上面用到這些類型構建一個復雜的Java對象,並完成JSON轉換。

@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();
  }
}

運轉後,後果如下:

jsonGenerator
"aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac worl "hello world jackson!" "hello world jackson!"
 {"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]} 
{"user":{"address":"address","name":"haha","id":1,"birthday":null,"email":"email"},"infos":["a","b","c"]}

怎樣樣?結構的json字符串和輸入的後果是分歧的吧。關鍵看懂用JSONGenerator提供的辦法,完成一個Object的構建。

三、JSON轉換成Java對象

1、 將json字符串轉換成JavaBean對象

@Test
public void readJson2Entity() {
  String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
  try {
    AccountBean acc = objectMapper.readValue(json, AccountBean.class);
    System.out.println(acc.getName());
    System.out.println(acc);
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

很復雜,用到了ObjectMapper這個對象的readValue這個辦法,這個辦法需求提供2個參數。第一個參數就是解析的JSON字符串,第二個參數是行將將這個JSON解析吃什麼Java對象,Java對象的類型。當然,還有其他相反簽名辦法,假如你有興味可以逐個嘗試運用辦法,當然運用的辦法和以後運用的辦法迥然不同。運轉後,後果如下:

haha
haha#1#address#null#email

2、 將json字符串轉換成List<Map>集合

/**
 * <b>function:</b>json字符串轉換成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();
  }
}

嘗試過將下面的JSON轉換成List,然後List中寄存AccountBean,但後果失敗了。但是支持Map集合。由於你轉成List.class,但是不知道List寄存何品種型。只好默然Map類型。由於一切的對象都可以轉換成Map結合,運轉後後果如下:

2
address:address2
name:haha2
id:2
email:email2
address:address
name:haha
id:1
email:email

3、 Json字符串轉換成Array數組,由於下面的泛型轉換不能辨認到集合中的對象類型。一切這裡用對象數組,可以處理這個問題。只不過它不再是集合,而是一個數組。當然這個不重要,你可以用Arrays.asList將其轉換成List即可。

/**
 * <b>function:</b>json字符串轉換成Array
 * @author hoojo
 */
@Test
public void readJson2Array() {
  String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
      "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
  try {
    AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
    System.out.println(arr.length);
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
    
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

運轉後的後果:

2
haha2#2#address2#null#email2
haha#1#address#null#email

4、 Json字符串轉換成Map集合

/**
 * <b>function:</b>json字符串轉換Map集合
 * @author hoojo */
@Test
public void readJson2Map() {
  String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
        "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
  try {
    Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
    System.out.println(maps.size());
    Set<String> key = maps.keySet();
    Iterator<String> iter = key.iterator();
    while (iter.hasNext()) {
      String field = iter.next();
      System.out.println(field + ":" + maps.get(field));
    }
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

運轉後後果如下:

3
success:true
A:{address=address2, name=haha2, id=2, email=email2}
B:{address=address, name=haha, id=1, email=email}

四、Jackson對XML的支持

Jackson也可以完成java對象到xml的轉換,轉換後的後果要比json-lib更直觀,不過它依賴於stax2-api.jar這個jar包。

/**
 * <b>function:</b>java對象轉換成xml文檔
 * 需求額定的jar包 stax2-api.jar
 * @author hoojo
 */
@Test
public void writeObject2Xml() {
  //stax2-api-3.0.2.jar
  System.out.println("XmlMapper");
  XmlMapper xml = new XmlMapper();
  
  try {
    //javaBean轉換成xml
    //xml.writeValue(System.out, bean);
    StringWriter sw = new StringWriter();
    xml.writeValue(sw, bean);
    System.out.println(sw.toString());
    //List轉換成xml
    List<AccountBean> list = new ArrayList<AccountBean>();
    list.add(bean);
    list.add(bean);
    System.out.println(xml.writeValueAsString(list));
    
    //Map轉換xml文檔
    Map<String, AccountBean> map = new HashMap<String, AccountBean>();
    map.put("A", bean);
    map.put("B", bean);
    System.out.println(xml.writeValueAsString(map));
  } catch (JsonGenerationException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

運轉下面的辦法,後果如下:

XmlMapper
<unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></unknown>
<unknown><unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></unknown>
<email><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></email></unknown>
<unknown><A><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></A>
<B><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></B></unknown>

看後果,根節點都是unknown 這個問題還沒有處理,由於根節點沒有轉換出來,一切招致解析xml到Java對象,也無法完成。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved