Java工具-JsonObject&JsonArray/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 方式方法与顺序问题

©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页