java中Array/List/Map/Object与Json互相转换详解

时间:2023-03-08 15:41:20

http://blog.****.net/xiaomu709421487/article/details/51456705

JSON(JavaScript Object Notation): 是一种轻量级的数据交换格式

一、JSON建构有两种结构:对象和数组

1、对象:对象在js中表示为“{}”扩起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。
2、数组:数组在js中是中括号“[]”扩起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。
经过对象、数组2种结构就可以组合成复杂的数据结构了。
二、具体形式
1、对象

(1)一个对象以“{”(左括号)开始,“}”(右括号)结束。

(2)每个“名称”后跟一个“:”(冒号)
(3)“‘名称/值’ 对”之间使用“,”(逗号)分隔
例子:表示人的一个对象:
{
"姓名" : "大憨",
"年龄" : 24
}
2、数组是值(value)的有序集合。
(1)一个数组以“[”(左中括号)开始,“]”(右中括号)结束。
(2)值之间使用“,”(逗号)分隔。
例子:一组学生
{
"学生" :
[
{"姓名" : "小明" , "年龄" : 23},
{"姓名" : "大憨" , "年龄" : 24}
]
}
说明:此Json对象包括了一个学生数组,而学生数组中的值又是两个Json对象。

说了这些基本了解json的数据结构了...

补充:在线Json校验格式化工具:http://www.bejson.com/go.php?u=http://www.bejson.com/index.php

三、老样子上次demo

这时我的工程结构图:上面引用到的外部库大家网上搜索下载~

java中Array/List/Map/Object与Json互相转换详解

configdata.json:

  1. [
  2. true,
  3. false,
  4. true
  5. ]

Address类:

  1. /**
  2. * @Title: 创建Address实体类的POJO
  3. * @Description: TODO(用一句话描述该文件做什么)
  4. * @author Potter
  5. * @date 2013-2-18 上午10:16:03
  6. * @version V1.0
  7. */
  8. public class Address {
  9. private String street;//街道
  10. private String city;//城市
  11. private int zip;//邮编
  12. private String tel;//第一个电话号码
  13. private String telTwo;//第二个电话号码
  14. public Address() {
  15. }
  16. public Address(String street, String city, int zip, String tel, String telTwo){
  17. this.street = street;
  18. this.city = city;
  19. this.zip = zip;
  20. this.tel = tel;
  21. this.telTwo = telTwo;
  22. }
  23. public String getStreet() {
  24. return street;
  25. }
  26. public void setStreet(String street) {
  27. this.street = street;
  28. }
  29. public String getCity() {
  30. return city;
  31. }
  32. public void setCity(String city) {
  33. this.city = city;
  34. }
  35. public int getZip() {
  36. return zip;
  37. }
  38. public void setZip(int zip) {
  39. this.zip = zip;
  40. }
  41. public String getTel() {
  42. return tel;
  43. }
  44. public void setTel(String tel) {
  45. this.tel = tel;
  46. }
  47. public String getTelTwo() {
  48. return telTwo;
  49. }
  50. public void setTelTwo(String telTwo) {
  51. this.telTwo = telTwo;
  52. }
  53. }

JsonTest类:

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.LinkedHashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import net.sf.ezmorph.bean.MorphDynaBean;
  10. import net.sf.json.JSONArray;
  11. import net.sf.json.JSONFunction;
  12. import net.sf.json.JSONObject;
  13. public class JsonTest {
  14. public static void main(String args[]) {
  15. //javaArray和json互相转换
  16. javaArrayAndJsonInterChange();
  17. System.out.println("-------------------------------------");
  18. //javaList和json互相转换
  19. javaListAndJsonInterChange();
  20. System.out.println("-------------------------------------");
  21. //javaMpa和Json互转
  22. javaMapAndJsonInterChange();
  23. System.out.println("-------------------------------------");
  24. //javaObject和jsonObject互转
  25. javaObjectAndJsonInterChange();
  26. }
  27. /**
  28. * javaArray和json互相转换
  29. */
  30. public static void javaArrayAndJsonInterChange() {
  31. // java 转数组
  32. boolean[] boolArray = new boolean[] { true, false, true };
  33. JSONArray jsonArray = JSONArray.fromObject(boolArray);
  34. String s = jsonArray.toString();
  35. System.out.println(s);
  36. // 通过json获取数组中的数据
  37. String result = readJson("configdata");
  38. JSONArray jsonR = JSONArray.fromObject(result);
  39. int size = jsonR.size();
  40. for (int i = 0; i < size; i++) {
  41. System.out.println(jsonR.get(i));
  42. }
  43. }
  44. /**
  45. * javaList和json互相转换
  46. */
  47. public static void javaListAndJsonInterChange() {
  48. List list = new ArrayList();
  49. list.add(new Integer(1));
  50. list.add(new Boolean(true));
  51. list.add(new Character('j'));
  52. list.add(new char[] { 'j', 's', 'o', 'n' });
  53. list.add(null);
  54. list.add("json");
  55. list.add(new String[] { "json", "-", "lib" });
  56. // list转JSONArray
  57. JSONArray jsArr = JSONArray.fromObject(list);
  58. System.out.println(jsArr.toString(4));
  59. // 从JSON串到JSONArray
  60. jsArr = JSONArray.fromObject(jsArr.toString());
  61. // --从JSONArray里读取
  62. // print: json
  63. System.out.println(((JSONArray) jsArr.get(6)).get(0));
  64. }
  65. /**
  66. * javaMpa和Json互转
  67. */
  68. public static void javaMapAndJsonInterChange() {
  69. Map map = new LinkedHashMap();
  70. map.put("integer", new Integer(1));
  71. map.put("boolean", new Boolean(true));
  72. map.put("char", new Character('j'));
  73. map.put("charArr", new char[] { 'j', 's', 'o', 'n' });
  74. // 注:不能以null为键名,否则运行报net.sf.json.JSONException:
  75. // java.lang.NullPointerException:
  76. // JSON keys must not be null nor the 'null' string.
  77. map.put("nullAttr", null);
  78. map.put("str", "json");
  79. map.put("strArr", new String[] { "json", "-", "lib" });
  80. map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)"));
  81. map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098"));
  82. // map转JSONArray
  83. JSONObject jsObj = JSONObject.fromObject(map);
  84. System.out.println(jsObj.toString(4));
  85. // 从JSON串到JSONObject
  86. jsObj = JSONObject.fromObject(jsObj.toString());
  87. //第一种方式:从JSONObject里读取
  88. // print: json
  89. System.out.println(jsObj.get("str"));
  90. // print: address.city = Seattle, WA
  91. System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));
  92. //第二种方式:从动态Bean里读取数据,由于不能转换成具体的Bean,感觉没有多大用处
  93. MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);
  94. // print: json
  95. System.out.println(mdBean.get("str"));
  96. //print: address.city = Seattle, WA
  97. System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));
  98. }
  99. /**
  100. * javaObject和jsonObject互转
  101. */
  102. public static void  javaObjectAndJsonInterChange(){
  103. Address address=new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098");
  104. //object转JSONObject
  105. JSONObject jsObj = JSONObject.fromObject(address);
  106. System.out.println(jsObj.toString(4));
  107. //JsonObject转java Object
  108. Address addressResult=(Address) JSONObject.toBean(jsObj, Address.class);
  109. System.out.println("address.city = "+ addressResult.getCity());
  110. System.out.println("address.street="+addressResult.getStreet());
  111. System.out.println("address.tel = "+ addressResult.getTel());
  112. System.out.println("address.telTwo="+addressResult.getTelTwo());
  113. System.out.println("address.zip="+addressResult.getZip());
  114. }
  115. /**
  116. * 读取json文件
  117. * @param fileName 文件名,不需要后缀
  118. * @return
  119. */
  120. public static String readJson(String fileName) {
  121. String result = null;
  122. try {
  123. File myFile = new File("./config/" + fileName + ".json");
  124. FileReader fr = new FileReader(myFile);
  125. char[] contents = new char[(int) myFile.length()];
  126. fr.read(contents, 0, (int) myFile.length());
  127. result = new String(contents);
  128. fr.close();
  129. } catch (FileNotFoundException e) {
  130. e.printStackTrace();
  131. } catch (IOException e) {
  132. e.printStackTrace();
  133. }
  134. return result;
  135. }
  136. }
java中Array/List/Map/Object与Json互相转换详解

哈哈~  没想到其实挺简单的!!!