网站建设公司好不好,网站服务器 维护,社区工作者有编制吗,智慧团建官方登录Fastjson是阿里巴巴的一个开源项目#xff0c;它是一个高性能的Java语言实现的JSON库。下面是如何使用Fastjson将Java对象转换为JSON对象的示例。
下载安装
需要将Fastjson库添加到项目的依赖中。如果您使用的是Maven#xff0c;可以在pom.xml文件中添加以下依赖#xff1…Fastjson是阿里巴巴的一个开源项目它是一个高性能的Java语言实现的JSON库。下面是如何使用Fastjson将Java对象转换为JSON对象的示例。
下载安装
需要将Fastjson库添加到项目的依赖中。如果您使用的是Maven可以在pom.xml文件中添加以下依赖
dependencygroupIdcom.alibaba/groupIdartifactIdfastjson/artifactIdversion1.2.83/version
/dependencyJSON对象转换为JSON字符串
package org.example;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;import java.text.SimpleDateFormat;
import java.util.Date;public class Main {public static void main(String[] args) throws Exception {SimpleDateFormat sdf new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);Date date sdf.parse(2023-11-09 22:11:59);JSONObject jsonObject new JSONObject().fluentPut(key1, date).fluentPut(key2, new JSONObject().fluentPut(key2.1, 2.1)).fluentPut(key3, new JSONArray().fluentAdd(1).fluentAdd(2));System.out.println(jsonObject.toJSONString());}
}{key1:1699539119000,key2:{key2.1:2.1},key3:[1,2]}用美化输出JSON字符串
package org.example;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;import java.text.SimpleDateFormat;
import java.util.Date;public class Main {public static void main(String[] args) throws Exception {SimpleDateFormat sdf new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);Date date sdf.parse(2023-11-09 22:11:59);JSONObject jsonObject new JSONObject().fluentPut(key1, date).fluentPut(key2, new JSONObject().fluentPut(key2.1, 2.1)).fluentPut(key3, new JSONArray().fluentAdd(1).fluentAdd(2));System.out.println(JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat));}
}这里使用了SerializerFeature.PrettyFormat它会以一种更易于阅读的方式包含换行符和缩进格式化输出的JSON字符串。如果不使用这个选项输出的JSON字符串将不会有任何格式。
{key1:1699539119000,key2:{key2.1:2.1},key3:[1,2]
}解析JSON字符串
package org.example;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;public class Main {public static void main(String[] args) throws Exception {String jsonString {key1:1,key2:{key2.1:2.1},key3:[1,2]};JSONObject jsonObject JSON.parseObject(jsonString);JSONObject key2 (JSONObject) jsonObject.get(key2);System.out.println(key2.get(key2.1)); // 2.1JSONArray key3 (JSONArray) jsonObject.get(key3);System.out.println(key3.get(1)); // 2}
}这里使用JSON.parseObject解析json字符串成JSONObject对象。
参考
https://github.com/alibaba/fastjson/wiki https://zhuanlan.zhihu.com/p/72495484