一.使用Gson转换为json格式
依赖的maven包:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
关键代码如下:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
//....
Gson gson = new GsonBuilder().create();
gson.toJson("Hello", System.out);
gson.toJson(123, System.out);
System.out.println();
JsonObject json = new JsonObject();
json.addProperty("dd", "22");
json.addProperty("dds", 22);
System.out.println(json);
输出:
"Hello"123
{"dd":"22","dds":22}
第二 .使用Json-lib转换json格式
Json-lib 是一个 Java 类库(官网:http://json-lib.sourceforge.net/)可以实现如下功能:
.转换 javabeans, maps, collections, java arrays 和 XML 成为 json 格式数据
.转换 json 格式数据成为 javabeans 对象
Json-lib 需要的 jar 包
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
Json-lib 的使用
1. 将 Array 解析成 Json 串。使用 JSONArray 可以解析 Array 类型:
package util.copy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class test {
public static void main(String[] args) {
JSONObject json2 = new JSONObject();
json2.put("ss", "55");
System.out.println(json2);
//将 Array 解析成 Json 串
String[] str = { "Jack", "Tom", "90", "true" };
JSONArray json = JSONArray.fromObject(str);
System.err.println(json);
//对像数组,注意数字和布而值
Object[] o = { "北京", "上海", 89, true, 90.87 };
json = JSONArray.fromObject(o);
System.err.println(json);
//使用集合类
List<String> list = new ArrayList<String>();
list.add("Jack");
list.add("Rose");
json = JSONArray.fromObject(list);
System.err.println(json);
//使用 set 集
Set<Object> set = new HashSet<Object>();
set.add("Hello");
set.add(true);
set.add(99);
json = JSONArray.fromObject(set);
System.err.println(json);
}
}
运行结果如下:
{"ss":"55"}
["Jack","Tom","90","true"]
["北京","上海",89,true,90.87]
["Jack","Rose"]
[99,true,"Hello"]
2. 将 JavaBean/Map 解析成 JSON 串。 使用JSONObject 解析:
public static void main(String[] args) {
//解析 HashMap
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Tom");
map.put("age", 33);
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);
//解析 JavaBean
Person person = new Person("A001", "Jack");
jsonObject = jsonObject.fromObject(person);
System.out.println(jsonObject);
//解析嵌套的对象
map.put("person", person);
jsonObject = jsonObject.fromObject(map);
System.out.println(jsonObject);
}
{"age":33,"name":"Tom"}
{"id":"A001","name":"Jack"}
{"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}
3. 使用 JsonConfig 过虑属性:适用于 JavaBean/Map
public static void main(String[] args) {
JsonConfig config = new JsonConfig();
config.setExcludes(new String[] { "name" }); // 指定在转换时不包含哪些属性
Person person = new Person("A001", "Jack");
JSONObject jsonObject = JSONObject.fromObject(person, config); // 在转换时传入之前的配置对象 System.out.println(jsonObject);
}
运行结果如下,在运行结果中我们可以看到 name 属性被过滤掉了:
{"id":"A001"}
4. 将 Json 串转换成 Array:
public static void main(String[] args) {
JSONArray jsonArray = JSONArray.fromObject("[89,90,99]");
Object array = JSONArray.toArray(jsonArray);
System.out.println(array);
System.out.println(Arrays.asList((Object[]) array));
}
运行结果如下:
[Ljava.lang.Object;@1e5003f6
[89, 90, 99]
5. 将 Json 串转成 JavaBean/Map:
public static void main(String[] args) {
//将 Json 形式的字符串转换为 Map
String str = "{\"name\":\"Tom\",\"age\":90}";
JSONObject jsonObject = JSONObject.fromObject(str);
Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
System.out.println(map);
//将 Json 形式的字符串转换为 JavaBean
str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
jsonObject = JSONObject.fromObject(str);
System.out.println(jsonObject);
Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
System.out.println(person);
}
运行结果如下:
{age=90, name=Tom}
Person [id=A001, name=Jack]
在将 Json 形式的字符串转换为 JavaBean 的时候需要注意 JavaBean 中必须有无参构造函数,否则会报如下找不到初始化方法的错误:
Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
at net.sf.json.JSONObject.toBean(JSONObject.java:288)
at net.sf.json.JSONObject.toBean(JSONObject.java:233)
at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
at net.sf.json.JSONObject.toBean(JSONObject.java:282)
... 2 more
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。