分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

数据转换为json格式

发布时间:2023-09-06 01:16责任编辑:郭大石关键词:jsjson

一.使用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




本文出自 “10916470” 博客,转载请与作者联系!

数据转换为json格式

原文地址:http://10926470.blog.51cto.com/10916470/1971253

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved