java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > fastjson常见API

关于fastjson的常见API详解

作者:尽力漂亮

这篇文章主要介绍了关于fastjson的常见API详解,Fastjson是一个Java库,可用于将Java对象转换为其JSON表示,它还可用于将JSON字符串转换为等效的Java对象,Fastjson可以处理任意Java对象,包括您没有源代码的预先存在的对象,需要的朋友可以参考下

简介

首先,介绍一下fastjson。fastjson是由alibaba开源的一套json处理器。与其他json处理器(如Gson,Jackson等)和其他的Java对象序列化反序列化方式相比,有比较明显的性能优势。

maven 添加配置:

< !-- 阿里fastjson包JSON转换–>
< dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
< /dependency>

常见API

1. 将对象序列化成json字符串

String com.alibaba.fastjson.JSON.toJSONString(Object object)

效果

{
	"l_factory": [{
		"fcName": "淘宝",
		"l_worker": [{
			"age": 26,
			"name": "李飞",
			"sex": "男"
		}, {
			"age": 0
		}, {
			"age": 0
		}, {
			"age": 0
		}]
	}, {
		"fcName": "拼多多",
		"l_worker": []
	}],
	"pjName": "接口自动化",
	"waibao": true
}

2. 将json字符串反序列化成对象 Project

com.alibaba.fastjson.JSON.parseObject(String text, Class clazz)

 System.out.println("parseObject 将json字符串反序列化成对象------" + "waibao="+ testFastJson.getJsonValueObj(json, "waibao", Boolean.class));

效果

 waibao=true

3. 将json字符串反序列化成JSON对象 JSONObject

com.alibaba.fastjson.JSON.parseObject(String text)

[{
	"l_worker": [{
		"sex": "男",
		"name": "张三",
		"age": 39
	}, {
		"sex": "男",
		"name": "李四",
		"age": 24
	}],
	"fcName": "淘宝"
}, {
	"l_worker": [{
		"sex": "女",
		"name": "王香",
		"age": 26
	}, {
		"sex": "男",
		"name": "李飞",
		"age": 26
	}],
	"fcName": "拼多多"
}]

4. 根据key 得到json中的json数组 JSONArray

com.alibaba.fastjson.JSONObject.getJSONArray(String key)

[{
	"sex": "男",
	"name": "张三",
	"age": 39
}, {
	"sex": "男",
	"name": "李四",
	"age": 24
}]
[{
	"sex": "男",
	"name": "张三",
	"age": 39
}, {
	"sex": "男",
	"name": "李四",
	"age": 24
}]

5. 根据下标拿到json数组的json对象 JSONObject

com.alibaba.fastjson.JSONArray.getJSONObject(int index)

效果

{
	"sex": "男",
	"name": "张三",
	"age": 39
}

6.根据key拿到json的字符串值 String

com.alibaba.fastjson.JSONObject.getString(String key)

api详细案例

Project

package com.json;
import java.util.List;
public class Project {
    String pjName;
    boolean waibao;
    public boolean isWaibao() {
        return waibao;
    }
    public void setWaibao(boolean waibao) {
        this.waibao = waibao;
    }
    List<Factory> l_factory;
    //List<Worker> worker;
    public String getPjName() {
        return pjName;
    }
    public void setPjName(String pjName) {
        this.pjName = pjName;
    }
    public List<Factory> getL_factory() {
        return l_factory;
    }
    public void setL_factory(List<Factory> l_factory) {
        this.l_factory = l_factory;
    }
}

Factory

package com.json;
import java.util.List;
public class Factory {
    String fcName;
    List<Worker> l_worker;
    public String getFcName() {
        return fcName;
    }
    public void setFcName(String fcName) {
        this.fcName = fcName;
    }
    public List<Worker> getL_worker() {
        return l_worker;
    }
    public void setL_worker(List<Worker> l_worker) {
        this.l_worker = l_worker;
    }
}

Worker

package com.json;
public class Worker {
    String name;
    String sex;
    int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}

TestFastJson

package com.json;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestFastJson {
	public static void main(String[] args) {
		TestFastJson testFastJson = new TestFastJson();
		Project project = testFastJson.init();
		String json = testFastJson.getJsonString(project);
		// System.out.println("json="+json);
		// {"l_factory":[{"fcName":"淘宝","l_worker":[{"age":26,"name":"李飞","sex":"男"},{"age":0},{"age":0},{"age":0}]},{"fcName":"拼多多","l_worker":[]}],"pjName":"接口自动化","waibao":true}
		// System.out.println("parseObject 将json字符串反序列化成对象------" + "waibao="
		// + testFastJson.getJsonValueObj(json, "waibao", Boolean.class));
		// waibao=true
		JSONArray array = (JSONArray) testFastJson.getJsonValueObj(json, "l_factory", JSONArray.class);
		// System.out.println("array=" + array.toString());
		// array=[{"l_worker":[{"sex":"男","name":"张三","age":39},{"sex":"男","name":"李四","age":24}],"fcName":"淘宝"},{"l_worker":[{"sex":"女","name":"王香","age":26},{"sex":"男","name":"李飞","age":26}],"fcName":"拼多多"}]
		// String jsonArr = testFastJson.getJsonArrayValue(array, 0, "fcName");
		// System.out.println("fcname:" + jsonArr);
		// fcname:淘宝
		JSONArray array2 = testFastJson.getJsonArrayValueIsArray(array, 0, "l_worker");
		// System.out.println("array2=" + array2.toString());
		// array2=[{"sex":"男","name":"张三","age":39},{"sex":"男","name":"李四","age":24}]
		String json2 = testFastJson.getJsonArrayValue(array2, 0);
		// System.out.println("json2="+json2);
		// {"sex":"男","name":"张三","age":39}
		// System.out.println("name"+testFastJson.getJsonValueObj(json, key, clazz));
		/*
		 * 以下输出 name=张三 sex=男 age=39 jsonArr2=男
		 * 
		 */
		System.out.println("name=" + testFastJson.getJsonValueObj(json2, "name", String.class));
		System.out.println("sex=" + testFastJson.getJsonValueObj(json2, "sex", String.class));
		System.out.println("age=" + testFastJson.getJsonValueObj(json2, "age", Integer.class));
		String jsonArr2 = testFastJson.getJsonArrayValue(array2, 0, "sex");
		System.out.println("jsonArr2=" + jsonArr2);
		/*
		 * 接口自动化 淘宝 张三
		 * 
		 */
		System.out.println(testFastJson.getJsonValue(json));
		System.out.println(testFastJson.getJsonValue(json, "l_factory"));
		System.out.println(testFastJson.getJsonValue(json, "l_factory", "l_worker"));
	}
	public static void main1(String args[]) {
		TestFastJson tfj = new TestFastJson();
		Project prj = tfj.init();
		String json = tfj.getJsonString(prj);
		prj.setPjName("序列化后修改pjname");
		System.out.println(prj.getPjName());// 序列化后修改pjname
		Project po = JSON.parseObject(json, Project.class);
		System.out.println(po.getPjName());// 接口自动化
	}
	public void tt(Class clazz) {
		System.out.println(clazz.getSimpleName());
		if (clazz.getName().equals("String")) {
			System.out.println("stringllala");
		}
	}
	/**
	 * 将对象转化为json
	 * 
	 * @param project
	 * @return
	 */
	private String getJsonString(Object object) {
		// TODO Auto-generated method stub
		String json = JSON.toJSONString(object);
		return json;
	}
	/**
	 * 初始化
	 * 
	 * @return
	 */
	private Project init() {
		Project project = new Project();
		Factory f1 = new Factory();
		Factory f2 = new Factory();
		Worker wk1 = new Worker();
		wk1.setName("张三");
		wk1.setAge(39);
		wk1.setSex("男");
		Worker wk2 = new Worker();
		wk2.setName("李四");
		wk2.setAge(24);
		wk2.setSex("男");
		Worker wk3 = new Worker();
		wk3.setName("王香");
		wk3.setAge(26);
		wk3.setSex("女");
		Worker wk4 = new Worker();
		wk4.setName("李飞");
		wk4.setAge(26);
		wk4.setSex("男");
		List<Worker> workers1 = new ArrayList<>();
		workers1.add(wk1);
		workers1.add(wk2);
		List<Worker> workers2 = new ArrayList<>();
		workers2.add(wk3);
		workers2.add(wk4);
		f1.setFcName("淘宝");
		f1.setL_worker(workers1);
		f2.setFcName("拼多多");
		f2.setL_worker(workers2);
		List<Factory> factorys = new ArrayList<Factory>();
		factorys.add(f1);
		factorys.add(f2);
		project.setPjName("接口自动化");
		project.setWaibao(true);
		project.setL_factory(factorys);
		return project;
	}
	/**
	 * 根据key得到json的value
	 * 
	 */
	public String getJsonValue(String json) {
		JSONObject jsonObject = JSON.parseObject(json);
		String value = jsonObject.getString("pjName");
		return value;
	}
	/**
	 * 根据对象的类型,自动识别获取该对象的值
	 */
	public Object getJsonValueObj(String json, String key, Class clazz) {
		JSONObject jo = JSON.parseObject(json);
		if (clazz.getSimpleName().equals("String")) {
			String value = jo.getString(key);
			return value;
		} else if (clazz.getSimpleName().equals("Integer")) {
			Integer value = jo.getInteger(key);
			return value;
		} else if (clazz.getSimpleName().equals("Boolean")) {
			Boolean value = jo.getBoolean(key);
			return value;
		} else if (clazz.getSimpleName().equals("JSONArray")) {
			JSONArray array = jo.getJSONArray(key);
			return array;
		} else {
			return "error, 暂不支持的类型:" + clazz.toString();
		}
	}
	/**
	 * 根据key得到json的集合
	 * 
	 */
	public JSONArray getJsonArray(String json, String key) {
		JSONObject jo = JSON.parseObject(json);
		JSONArray array = jo.getJSONArray(key);
		return array;
	}
	public String getJsonValue(String json, String key) {
		JSONObject jo = JSON.parseObject(json);
		JSONArray array = jo.getJSONArray(key);
		JSONObject jo_fc = array.getJSONObject(0);
		String value = jo_fc.getString("fcName");
		return value;
	}
	public String getJsonValue(String json, String key, String keyW) {
		JSONObject jo = JSON.parseObject(json);
		JSONArray array = jo.getJSONArray(key);
		JSONObject jo_fc = array.getJSONObject(0);
		JSONArray arrayW = jo_fc.getJSONArray(keyW);
		JSONObject jo_wk = arrayW.getJSONObject(0);
		String value = jo_wk.getString("name");
		int age = jo_wk.getIntValue("age");
		return value;
	}
	/**
	 * 根据下标得到json数组的值
	 * 
	 * @return
	 */
	public String getJsonArrayValue(JSONArray array, int index) {
		JSONObject jo_fc = array.getJSONObject(index);
		String json = jo_fc.toJSONString();
		return json;
	}
	/**
	 * 根据下标得到j'son数组的值,再根据key得到该值的value,该值类型是String
	 * 
	 * @param array
	 * @param index
	 * @param key
	 * @return
	 */
	public String getJsonArrayValue(JSONArray array, int index, String key) {
		JSONObject jo_fc = array.getJSONObject(index);
		String value = jo_fc.getString(key);
		return value;
	}
	/**
	 * 根据下标得到json数组的值,再根据key得到该值的value,该值类型是string
	 * 
	 * @param array
	 * @return
	 */
	public JSONArray getJsonArrayValueIsArray(JSONArray array, int index, String key) {
		JSONObject jo_fc = array.getJSONObject(index);
		JSONArray arrayNew = jo_fc.getJSONArray(key);
		return arrayNew;
	}
}

到此这篇关于关于fastjson的常见API详解的文章就介绍到这了,更多相关fastjson常见API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文