Java工具-Json/Object/String相互轉換(FastJson)

前言

之前處理Json類型字符串. 對於相關細節有些疏忽了(Spark SQL 導入JSON文件).
藉此機會將Json類型字符串全部梳理一遍.


Maven 引用

  <dependencies>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.4</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
  </dependencies>

Json 相關表示類型

  • Object對象(單個)
{"name":"sean","age":18,"sex":"male"}
  • Object對象(多個)
{"name":"sean","age":18,"sex":"male"},
{"name":"coal","age":18,"sex":"male"}
  • 數組&List
[{"age":18,"sex":"male","name":"Sean"},{"age":18,"sex":"male","name":"bruce"},{"age":18,"sex":"male","name":"gogogo"}]
  • Map
{"sean":"hello","bruce":"gogogo"}
  • 複雜數據類型(混合類)
{"list":["ListValue1","ListValue2"],"map":{"map2":"mapValue2","map1":"mapValue1"},"name":"sean","stringArray":["stringValue1","stringValue2"]}

相關POJO

  • People
import com.alibaba.fastjson.annotation.JSONField;

public class People {
	@JSONField(ordinal = 1)
	public String name;
	
	// @JSONField()
	public Integer age;
	public String sex;
	
	public People() {}

	public People(String name,Integer age,String sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
}
  • ComplexPeople
package com.yanxml.arsenal.java.json.pojo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ComplexPeople {
	
	String name;
	Map<String ,String> map;
	List<String> list;
	String [] stringArray;
	
	
	public ComplexPeople() {
		name  = "sean";
		
		// Map
		map = new HashMap();
		map.put("map1", "mapValue1");
		map.put("map2", "mapValue2");
		
		// List
		list = new ArrayList<String>();
		list.add("ListValue1");
		list.add("ListValue2");
		
		stringArray = new String[2];
		stringArray[0]="stringValue1";
		stringArray[1]="stringValue2";
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public Map<String, String> getMap() {
		return map;
	}


	public void setMap(Map<String, String> map) {
		this.map = map;
	}


	public List<String> getList() {
		return list;
	}


	public void setList(List<String> list) {
		this.list = list;
	}


	public String[] getStringArray() {
		return stringArray;
	}


	public void setStringArray(String[] stringArray) {
		this.stringArray = stringArray;
	}
	

}

轉換操作

  • Object 相關
//@Test
	public void testForObject() {
		// 轉換爲 JSONOBJECT
		String peopleJsonString = "{\"name\":\"sean\",\"age\":18,\"sex\":\"male\"}";
		JSONObject jsonObject = JSONObject.parseObject(peopleJsonString);
		String peopleName = (String)jsonObject.get("name");
		Integer peopleAge = (Integer)jsonObject.get("age");
		System.out.println("name:"+peopleName+" age:"+peopleAge);
		
		// 轉換爲Object
		People people = JSONObject.parseObject(peopleJsonString,People.class);
		System.out.println(people.getName()+" / "+people.getAge());
	}
	
	//@Test
	public void testForObjectToJson() {
		People people = new People("Sean", 18, "male");
		// 不指定順序 {"age":18,"name":"Sean","sex":"male"}
		String peopleJsonStr = JSONObject.toJSONString(people);
		System.out.println(peopleJsonStr);
		// 指定順序類型 -	@JSONField(ordinal = 1)
		
		// Object 轉換爲Jsonobject
		JSONObject object = (JSONObject) JSONObject.toJSON(people);
		System.out.println(object.get("name")+" : "+object.get("age"));
	}
  • 數組相關
//@Test
	public void testForArray() {
		// 轉換爲JsonObject
		String arrayJson = "[{\"age\":18,\"sex\":\"male\",\"name\":\"Sean\"},{\"age\":18,\"sex\":\"male\",\"name\":\"bruce\"},{\"age\":18,\"sex\":\"male\",\"name\":\"gogogo\"}]\n";
		JSONArray jsonArray = JSONObject.parseArray(arrayJson);
		System.out.println(jsonArray.get(1).toString());
		
		// 轉換爲ObjectArray
		List<People> peopleList = JSON.parseArray(arrayJson, People.class);
		
		People[] peopleArray = (People[])peopleList.toArray();
		
		// Array轉變爲List
		List<String> arrayList = Arrays.asList(new String[] {""});
	}
	
	
	//@Test
	public void testForArrayJson() {
		People[] peopleArray = new People[3];
		peopleArray[0] = new People("Sean",18,"male");
		peopleArray[1] = new People("bruce",18,"male");
		peopleArray[2] = new People("gogogo",18,"male");
		
		String jsonString = JSONObject.toJSONString(peopleArray);
		System.out.println(jsonString);
	}
  • Map相關
	// Map數據類型轉換
	//@Test
	public void testForMap() {
		String mapString = "{\"sean\":\"hello\",\"bruce\":\"gogogo\"}";
		JSONObject jsonObject = JSONObject.parseObject(mapString);
		Map<String,Object> map = (Map<String, Object>)jsonObject;
		
	}
	
	
	//@Test
	public void testForMapJson() {
		Map<String,String> map = new HashMap();
		map.put("sean", "hello");
		map.put("bruce", "gogogo");
		
		String jsonString = JSONObject.toJSONString(map);
		System.out.println(jsonString);
	}
  • 複雜數據類型相關
// 複雜數據類型轉換爲JsonString字符串
	//@Test
	public void testForComplexObject() {
		String jsonString = JSONObject.toJSONString(new ComplexPeople());
		System.out.println(jsonString);
		
		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(new ComplexPeople());
	}
	
	@Test
	public void testForComplexJson() {
		String jsonString ="{\"list\":[\"ListValue1\",\"ListValue2\"],\"map\":{\"map2\":\"mapValue2\",\"map1\":\"mapValue1\"},\"name\":\"sean\",\"stringArray\":[\"stringValue1\",\"stringValue2\"]}";
		// 轉換爲ComplexPeople實體類
		ComplexPeople complexPeople = JSONObject.parseObject(jsonString,ComplexPeople.class);
		System.out.println("map2:"+complexPeople.getMap().get("map2"));
		System.out.println("stringArray:"+complexPeople.getStringArray().toString());

		
		// 轉換爲JsonObject
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
	}

注意事項

  • 所有需要Json轉換的字段必須設置public, 或者設置public接口get/set方法.
  • 忽略某些字段 & 輸出Json順序. 可以使用框架的@JsonField實現. @JSONField(ordinal = 1)/@JSONField(serialize = false)
  • 其他Json標籤.
    在這裏插入圖片描述
  • Json必須有可以訪問的缺省構造函數. 否則報告如下異常.
com.alibaba.fastjson.JSONException: default constructor not found. class com.yanxml.arsenal.java.json.pojo.People
	at com.alibaba.fastjson.util.DeserializeBeanInfo.computeSetters(DeserializeBeanInfo.java:182)
	at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:469)
	at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:427)
	at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:348)
	at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:548)
	at com.alibaba.fastjson.JSON.parseObject(JSON.java:250)
	at com.alibaba.fastjson.JSON.parseObject(JSON.java:226)
	at com.alibaba.fastjson.JSON.parseObject(JSON.java:185)
	at com.alibaba.fastjson.JSON.parseObject(JSON.java:303

Reference

[1]. JAVA中使用alibaba fastjson實現JSONObject、Object、Json字符串的轉換
[2]. 阿里FastJson常見類型解析
[3]. 使用FastJSON 對Map/JSON/String 進行互相轉換
[4]. java對象轉JSONObject
[5]. fastjson --JSONObject 和JSONArray 轉換
[6]. Fastjson轉換時,忽略某字段
[7]. 對象轉json 方式方法與順序問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章