java中Array/List/Map/Object与Json互相转换详解
http://blog.csdn.net/xiaomu709421487/article/details/51456705
一、JSON建构有两种结构:对象和数组
(1)一个对象以“{”(左括号)开始,“}”(右括号)结束。
说了这些基本了解json的数据结构了...
补充:在线Json校验格式化工具:http://www.bejson.com/go.php?u=http://www.bejson.com/index.php
三、老样子上次demo
这时我的工程结构图:上面引用到的外部库大家网上搜索下载~

configdata.json:
- [
- true,
- false,
- true
- ]
Address类:
- /**
- * @Title: 创建Address实体类的POJO
- * @Description: TODO(用一句话描述该文件做什么)
- * @author Potter
- * @date 2013-2-18 上午10:16:03
- * @version V1.0
- */
- public class Address {
- private String street;//街道
- private String city;//城市
- private int zip;//邮编
- private String tel;//第一个电话号码
- private String telTwo;//第二个电话号码
- public Address() {
- }
- public Address(String street, String city, int zip, String tel, String telTwo){
- this.street = street;
- this.city = city;
- this.zip = zip;
- this.tel = tel;
- this.telTwo = telTwo;
- }
- public String getStreet() {
- return street;
- }
- public void setStreet(String street) {
- this.street = street;
- }
- public String getCity() {
- return city;
- }
- public void setCity(String city) {
- this.city = city;
- }
- public int getZip() {
- return zip;
- }
- public void setZip(int zip) {
- this.zip = zip;
- }
- public String getTel() {
- return tel;
- }
- public void setTel(String tel) {
- this.tel = tel;
- }
- public String getTelTwo() {
- return telTwo;
- }
- public void setTelTwo(String telTwo) {
- this.telTwo = telTwo;
- }
- }
JsonTest类:
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import net.sf.ezmorph.bean.MorphDynaBean;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONFunction;
- import net.sf.json.JSONObject;
- public class JsonTest {
- public static void main(String args[]) {
- //javaArray和json互相转换
- javaArrayAndJsonInterChange();
- System.out.println("-------------------------------------");
- //javaList和json互相转换
- javaListAndJsonInterChange();
- System.out.println("-------------------------------------");
- //javaMpa和Json互转
- javaMapAndJsonInterChange();
- System.out.println("-------------------------------------");
- //javaObject和jsonObject互转
- javaObjectAndJsonInterChange();
- }
- /**
- * javaArray和json互相转换
- */
- public static void javaArrayAndJsonInterChange() {
- // java 转数组
- boolean[] boolArray = new boolean[] { true, false, true };
- JSONArray jsonArray = JSONArray.fromObject(boolArray);
- String s = jsonArray.toString();
- System.out.println(s);
- // 通过json获取数组中的数据
- String result = readJson("configdata");
- JSONArray jsonR = JSONArray.fromObject(result);
- int size = jsonR.size();
- for (int i = 0; i < size; i++) {
- System.out.println(jsonR.get(i));
- }
- }
- /**
- * javaList和json互相转换
- */
- public static void javaListAndJsonInterChange() {
- List list = new ArrayList();
- list.add(new Integer(1));
- list.add(new Boolean(true));
- list.add(new Character('j'));
- list.add(new char[] { 'j', 's', 'o', 'n' });
- list.add(null);
- list.add("json");
- list.add(new String[] { "json", "-", "lib" });
- // list转JSONArray
- JSONArray jsArr = JSONArray.fromObject(list);
- System.out.println(jsArr.toString(4));
- // 从JSON串到JSONArray
- jsArr = JSONArray.fromObject(jsArr.toString());
- // --从JSONArray里读取
- // print: json
- System.out.println(((JSONArray) jsArr.get(6)).get(0));
- }
- /**
- * javaMpa和Json互转
- */
- public static void javaMapAndJsonInterChange() {
- Map map = new LinkedHashMap();
- map.put("integer", new Integer(1));
- map.put("boolean", new Boolean(true));
- map.put("char", new Character('j'));
- map.put("charArr", new char[] { 'j', 's', 'o', 'n' });
- // 注:不能以null为键名,否则运行报net.sf.json.JSONException:
- // java.lang.NullPointerException:
- // JSON keys must not be null nor the 'null' string.
- map.put("nullAttr", null);
- map.put("str", "json");
- map.put("strArr", new String[] { "json", "-", "lib" });
- map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)"));
- map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098"));
- // map转JSONArray
- JSONObject jsObj = JSONObject.fromObject(map);
- System.out.println(jsObj.toString(4));
- // 从JSON串到JSONObject
- jsObj = JSONObject.fromObject(jsObj.toString());
- //第一种方式:从JSONObject里读取
- // print: json
- System.out.println(jsObj.get("str"));
- // print: address.city = Seattle, WA
- System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));
- //第二种方式:从动态Bean里读取数据,由于不能转换成具体的Bean,感觉没有多大用处
- MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);
- // print: json
- System.out.println(mdBean.get("str"));
- //print: address.city = Seattle, WA
- System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));
- }
- /**
- * javaObject和jsonObject互转
- */
- public static void javaObjectAndJsonInterChange(){
- Address address=new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098");
- //object转JSONObject
- JSONObject jsObj = JSONObject.fromObject(address);
- System.out.println(jsObj.toString(4));
- //JsonObject转java Object
- Address addressResult=(Address) JSONObject.toBean(jsObj, Address.class);
- System.out.println("address.city = "+ addressResult.getCity());
- System.out.println("address.street="+addressResult.getStreet());
- System.out.println("address.tel = "+ addressResult.getTel());
- System.out.println("address.telTwo="+addressResult.getTelTwo());
- System.out.println("address.zip="+addressResult.getZip());
- }
- /**
- * 读取json文件
- * @param fileName 文件名,不需要后缀
- * @return
- */
- public static String readJson(String fileName) {
- String result = null;
- try {
- File myFile = new File("./config/" + fileName + ".json");
- FileReader fr = new FileReader(myFile);
- char[] contents = new char[(int) myFile.length()];
- fr.read(contents, 0, (int) myFile.length());
- result = new String(contents);
- fr.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return result;
- }
- }

哈哈~ 没想到其实挺简单的!!!
java中Array/List/Map/Object与Json互相转换详解的更多相关文章
- java中Array/List/Map/Object与Json互相转换详解(转载)
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programming Langu ...
- JAVA中list,set,map与数组之间的转换详解
package test; import java.util.*; /** * Created by ming */ public class Test { public static void ma ...
- JAVA中时间格式(SimpleDateFormat)和数字格式(DecimalFormat)转换详解(转)
时间格式转换SimpleDateFormat: //定义日期的格式 SimpleDateFormat format =new SimpleDateFormat("yyMMdd"); ...
- PHP中IP地址与整型数字互相转换详解
这篇文章主要介绍了PHP中IP地址与整型数字互相转换详解,本文介绍了使用PHP函数ip2long与long2ip的使用,以及它们的BUG介绍,最后给出自己写的两个算法,需要的朋友可以参考下 IP转换成 ...
- Java中数组判断元素存在几种方式比较详解
1. 通过将数组转换成List,然后使用List中的contains进行判断其是否存在 public static boolean useList(String[] arr,String contai ...
- java中String类、StringBuilder类和StringBuffer类详解
本位转载自http://www.cnblogs.com/dolphin0520/p/3778589.html 版权声明如下: 作者:海子 出处:http://www.cnblogs.com/dolp ...
- Java中的公平锁和非公平锁实现详解
前言 Java语言中有许多原生线程安全的数据结构,比如ArrayBlockingQueue.CopyOnWriteArrayList.LinkedBlockingQueue,它们线程安全的实现方式并非 ...
- java中装箱和拆箱的详细使用(详解)
一.什么是装箱?什么是拆箱? 在前面的文章中提到,Java为每种基本数据类型都提供了对应的包装器类型,至于为什么会为每种基本数据类型提供包装器类型在此不进行阐述,有兴趣的朋友可以查阅相关资料.在Jav ...
- Java中通过Class类获取Class对象的方法详解
方式1:通过Object类的getObject()方法 Person p = new Person(); Class c = p.getClass(); 方式2: 通过 类名.class 获取到字节码 ...
随机推荐
- WSF脚本详解:组合JS和VBS代码
1.概述 Windows Script Host除了提供一个对象模型之外,还提供了一种脚本框架,这就是WSF脚本.通过WSF约定的标记元素,可以将多种脚本语言写的代码块组合起来,完成任务.除此之外,还 ...
- eclipse安装zylin embedded cdt失败解决办法
最近再搞嵌入式开发,之前用惯了IDE调试单片机的那种方式,开发2440和am3358驱动时候无法方便的查看寄存器和变量,憋的抓耳挠腮,不爽得很,没有可视化环境进行实时调试观察,太特么蛋疼了.感觉这种情 ...
- CopyFile类通过调用这个类的delete(String filePath)方法可以组合成一个Cut类
package folderoperation; import java.io.File;/** * 注意它会删除文件,文件夹以及文件夹下的所有内容(根据指定的地址) * @author Dawn * ...
- 如何写一个HttpClient[1]——URI的处理
如何写一个HttpClient[1]--URI的处理 在翻阅apache的http client的代码的时候,看到org.apache.http.client.utils.URIBuilder.jav ...
- 用ssh整合时,用sessionfactory的getCurrentSession()获取不到session
在用ssh整合时,一开始用的是getCurrentSession(),获取当前线程上的session,但是总是抛异常,不能获取. 后来用sessionfactory的openSession(),但是, ...
- HTML、JavaScript之单双引号转义
一.HTML : 双引号:" 单引号:' 二.JavaScript: 双引号:\" 单引号:\'
- caffe model 可视化
1. 打开网址 http://ethereon.github.io/netscope/#/editor 2.将自己的train_test.prototxt里的复制粘贴到左边 3.然后同时shift+e ...
- 大理石在哪里UVa 10474
我自己写的代码 #include<iostream>#include<algorithm>using namespace std;int main(){ int N,a[ ...
- IIS出现Service Unavailable 错误
IIS访问操作出现以下问题时要如何解决:
- libevent源码分析:listener
listener是libevent封装的一个方便生成监听者的一组结构和函数,其中包括: /* * Copyright (c) 2000-2007 Niels Provos <provos@cit ...