编程中的Json
来源:互联网 发布:全民tv怎么没人了 知乎 编辑:程序博客网 时间:2024/05/22 22:42
1.首先区分json.jar与gson.jar:
⑴借助json.jar包即可完成json数据的封装以及解析
⑵gson.jar包可以用来解析json数据,对应的解析方法还有
①借助json.jar的传统解析方式
②FastJSON解析方式
总共三种
2.json数据的封装构造
⑴ List集合转换成json方法
List list = new ArrayList();list.add( "first" );list.add( "second" );JSONArray jsonArray2 = JSONArray.fromObject( list );
⑵Map集合转换成json方法
Map map = new HashMap();map.put("name", "json");map.put("bool", Boolean.TRUE);map.put("int", new Integer(1));map.put("arr", new String[] { "a", "b" });map.put("func", "function(i){ return this.arr[i]; }");JSONObject json = JSONObject.fromObject(map);
⑶Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
⑷数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
⑸一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
⑹beans转换成json代码
List list = new ArrayList();JsonBean2 jb1 = new JsonBean2();jb1.setCol(1);jb1.setRow(1);jb1.setValue("xx");JsonBean2 jb2 = new JsonBean2();jb2.setCol(2);jb2.setRow(2);jb2.setValue("");list.add(jb1);list.add(jb2);JSONArray ja = JSONArray.fromObject(list);
3.用法示例:
⑴示例一:
package com.json;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONArray;import net.sf.json.JSONObject;/** * 使用json-lib构造和解析Json数据 * * @author Alexia * @date 2013/5/23 * */public class JsonTest { /** * 构造Json数据 * * @return */ public static String BuildJson() { // JSON格式数据解析对象 JSONObject jo = new JSONObject(); // 下面构造两个map、一个list和一个Employee对象 Map<String, String> map1 = new HashMap<String, String>(); map1.put("name", "Alexia"); map1.put("sex", "female"); map1.put("age", "23"); Map<String, String> map2 = new HashMap<String, String>(); map2.put("name", "Edward"); map2.put("sex", "male"); map2.put("age", "24"); List<Map> list = new ArrayList<Map>(); list.add(map1); list.add(map2); Employee employee = new Employee(); employee.setName("wjl"); employee.setSex("female"); employee.setAge(24); // 将Map转换为JSONArray数据 JSONArray ja1 = JSONArray.fromObject(map1); // 将List转换为JSONArray数据 JSONArray ja2 = JSONArray.fromObject(list); // 将Bean转换为JSONArray数据 JSONArray ja3 = JSONArray.fromObject(employee); System.out.println("JSONArray对象数据格式:"); System.out.println(ja1.toString()); System.out.println(ja2.toString()); System.out.println(ja3.toString()); // 构造Json数据,包括一个map和一个Employee对象 jo.put("map", ja1); jo.put("employee", ja2); System.out.println("\n最终构造的JSON数据格式:"); System.out.println(jo.toString()); return jo.toString(); } /** * 解析Json数据 * * @param jsonString Json数据字符串 */ public static void ParseJson(String jsonString) { // 以employee为例解析,map类似 JSONObject jb = JSONObject.fromObject(jsonString); JSONArray ja = jb.getJSONArray("employee"); List<Employee> empList = new ArrayList<Employee>(); // 循环添加Employee对象(可能有多个) for (int i = 0; i < ja.size(); i++) { Employee employee = new Employee(); employee.setName(ja.getJSONObject(i).getString("name")); employee.setSex(ja.getJSONObject(i).getString("sex")); employee.setAge(ja.getJSONObject(i).getInt("age")); empList.add(employee); } System.out.println("\n将Json数据转换为Employee对象:"); for (int i = 0; i < empList.size(); i++) { Employee emp = empList.get(i); System.out.println("name: " + emp.getName() + " sex: " + emp.getSex() + " age: " + emp.getAge()); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ParseJson(BuildJson()); }}
⑵实例二:(自己写的)
package test;import org.json.JSONException;import org.json.JSONObject;public class JsonTest { private static String username; private static int age; public static void main(String[] args) { // TODO Auto-generated method stub JSONObject jsonObject = new JSONObject(); try { jsonObject.put("name", "张三"); jsonObject.put("age", 23); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(jsonObject.toString()); try { username = jsonObject.getString("name"); age = jsonObject.getInt("age"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(username); System.out.println(age); }}
⑶示例三(JSON解析之GSON)
①生成JSON字符串
import com.google.gson.Gson;public class JsonUtils { public static String createJsonObject(Object obj) { Gson gson = new Gson(); String str = gson.toJson(obj); return str; }}
②解析JSON
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
;
public class GsonTools {
public GsonTools() { // TODO Auto-generated constructor stub}/** * @param * @param jsonString * @param cls * @return */public static T getPerson(String jsonString, Class cls) { T t = null; try { Gson gson = new Gson(); t = gson.fromJson(jsonString, cls); } catch (Exception e) { // TODO: handle exception } return t;}/** * 使用Gson进行解析 List * * @param * @param jsonString * @param cls * @return */public static List getPersons(String jsonString, Class cls) { List list = new ArrayList(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken>() { }.getType()); } catch (Exception e) { } return list;}/** * @param jsonString * @return */public static List getList(String jsonString) { List list = new ArrayList(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list;}public static List> listKeyMaps(String jsonString) { List> list = new ArrayList>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list;}
}
⑷示例四(JSON解析之FastJSON)
import java.util.ArrayList;import java.util.List;import java.util.Map;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.TypeReference;public class JsonTool { public static T getPerson(String jsonstring, Class cls) { T t = null; try { t = JSON.parseObject(jsonstring, cls); } catch (Exception e) { // TODO: handle exception } return t; } public static List getPersonList(String jsonstring, Class cls) { List list = new ArrayList(); try { list = JSON.parseArray(jsonstring, cls); } catch (Exception e) { // TODO: handle exception } return list; } public static List> getPersonListMap1( String jsonstring) { List> list = new ArrayList>(); try { list = JSON.parseObject(jsonstring, new TypeReference>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list; }}
4.json.jar与json-lib-2.1.jar:
json-lib的使用需配合commons-beanutils-1.7.0.jar 、commons-lang-2.1.jar 、ezmorph-1.0.2.jar ,如果没有这几个包会报:
java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
阅读全文
0 0
- 编程中的Json
- 11.15课堂笔记-JSON对象、面向对象编程中的 this、Web Storage
- json-c 编程实例
- 网络编程:Json解析
- 如何使用json编程
- 网络编程5--JSON
- Java编程之JSON
- java json编程-1
- java json编程-2
- java json编程
- javascript中的json对象
- ActionScript3中的JSON数据格式
- JavaScript中的JSON
- JavaScript中的JSON
- JavaScript中的JSON
- JavaScript中的JSON
- JavaScript中的JSON
- Struts2中的json插件
- CSS3笔记——动画 animation
- Add Two Numbers
- Spring-MyBatis 之 MapperScannerConfigurer
- AngularJS ng-model 验证及监听
- generic operation system : process
- 编程中的Json
- Spark日志分析项目Demo(8)--SparkStream,广告点击流量实时统计
- C语言中返回错误信息的相关函数用法总结定义函数
- Moment.js
- C#的字符串操作方法性能比较
- python里使用事件对象asyncio.Event来同步协程
- 抓包神器Charles使用教程(一) 安装设置与界面
- redis 键管理
- Python 边做边学 N.1 成果展示--用户区域统计