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 方式方法与顺序问题

`com.alibaba.fastjson.JSONArray` 是阿里巴巴 Fastjson 库中的一个数据结构,它是一个动态数组,主要用于序列化和反序列化 JSON 数据。如果你想将 `JSONArray` 转换为普通的 Java 对象(如 List 或者自定义的对象),你可以按照以下步骤操作: 1. 首先,确保你要处理的 `JSONArray` 中的元素可以对应到你想要的目标对象的属性。Fastjson 通常支持自动反序列化,如果目标对象有相应的字段,它会尝试将 JSON 数据映射过去。 2. 使用 `JSONArray.toJSONString(Object obj)` 或者 `JSONArray.toJavaList(Class<T> clazz)` 方法。`toJSONString` 可以直接将整个数组转换JSON 字符串,然后解析成 Object。`toJavaList` 则会将 JSONArray 转换成指定类型的 List。 ```java // 示例:假设有一个自定义的 User 类 Class<User> clazz = User.class; JSONArray jsonArray = ...; // 你的 JSONArray // 如果想直接为字符串 String jsonString = jsonArray.toJSONString(); // 或者为 User 列表 List<User> userList = jsonArray.toJavaList(clazz); ``` 3. 如果需要对 JSON 内容进行更复杂的解析,比如自定义转换规则,你可以遍历 `JSONArray` 的每个元素,并创建对应的实例并填充数据。 ```java List<User> userList = new ArrayList<>(); for (Object item : jsonArray) { User user = clazz.newInstance(); // 根据item的内容设置user对象的属性 user.setName(((JSONObject) item).getString("name")); // 更多属性... userList.add(user); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值