json篇

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json篇相关的知识,希望对你有一定的参考价值。

json的各种解析:

  JSON(javascript Object Notation) 是一种轻量级的数据交换格式,相比较于xml交换数据的格式xml是重量级的数据交换格式。

JSON 语法是:
  数据在键值对中
  数据由逗号分隔
  花括号保存对象
  方括号保存数组

json解析比较常用,因为他是一种轻量级的数据交换方式,下面就来实际操作下json的解析。

  json可以将一个对象,数组,集合,map等转换为json格式的字符串。

  反之也可以将正确的json格式字符串转换为对象,数组,集合,map等。

json在不提交表单,异步向浏览器传递一个对象,这时用json就比较方便,因为我们只需导入相应的架包,向浏览器输出一个json格式的字符串,相应的jar包会帮我们解析。在向浏览器输出json格式的字符串是要注意将编码改为国际通用的编码,否则解析出来会出现乱码。

解析json关键的类:

  jackson 框架:这个框架提供了JsonGenerator   ,ObjectMapper两个类通过这两个类提供的方法可以将java 对象转化为json 对象,json 数组格式,也可以将json对象、数组格式转化为java对象。

接下来直接上相关解析的代码:

相关测试的实体类:

  BuyOrderDetail.java

技术分享
  1 package cn.hp.testjson;
  2 
  3 import java.io.Serializable;
  4 import java.math.BigDecimal;
  5 
  6 
  7 public class BuyOrderDetail implements Serializable {
  8     /**
  9      * 
 10      */
 11     private static final long serialVersionUID = 6829722529150944502L;
 12 
 13     private String bodId;
 14 
 15     private String goodsId;
 16 
 17     private String goodsName;
 18 
 19     private String goodsUint;
 20 
 21     @Override
 22     public String toString() {
 23         return "BuyOrderDetail [bodId=" + bodId + ", goodsId=" + goodsId
 24                 + ", goodsName=" + goodsName + ", goodsUint=" + goodsUint
 25                 + ", goodsType=" + goodsType + ", goodsColor=" + goodsColor
 26                 + ", bodAmount=" + bodAmount + ", bodBuyPrice=" + bodBuyPrice
 27                 + ", bodTotalPrice=" + bodTotalPrice + ", boId=" + boId
 28                 + ", bodImeiList=" + bodImeiList + "]";
 29     }
 30 
 31     private String goodsType;
 32 
 33     private String goodsColor;
 34 
 35     private Integer bodAmount;
 36 
 37     private BigDecimal bodBuyPrice;
 38 
 39     private BigDecimal bodTotalPrice;
 40 
 41     private String boId;
 42 
 43     private String bodImeiList;
 44 
 45     public String getBodId() {
 46         return bodId;
 47     }
 48 
 49     public void setBodId(String bodId) {
 50         this.bodId = bodId == null ? null : bodId.trim();
 51     }
 52 
 53     public String getGoodsId() {
 54         return goodsId;
 55     }
 56 
 57     public void setGoodsId(String goodsId) {
 58         this.goodsId = goodsId == null ? null : goodsId.trim();
 59     }
 60 
 61     public String getGoodsName() {
 62         return goodsName;
 63     }
 64 
 65     public void setGoodsName(String goodsName) {
 66         this.goodsName = goodsName == null ? null : goodsName.trim();
 67     }
 68 
 69     public String getGoodsUint() {
 70         return goodsUint;
 71     }
 72 
 73     public void setGoodsUint(String goodsUint) {
 74         this.goodsUint = goodsUint == null ? null : goodsUint.trim();
 75     }
 76 
 77     public String getGoodsType() {
 78         return goodsType;
 79     }
 80 
 81     public void setGoodsType(String goodsType) {
 82         this.goodsType = goodsType == null ? null : goodsType.trim();
 83     }
 84 
 85     public String getGoodsColor() {
 86         return goodsColor;
 87     }
 88 
 89     public void setGoodsColor(String goodsColor) {
 90         this.goodsColor = goodsColor == null ? null : goodsColor.trim();
 91     }
 92 
 93     public Integer getBodAmount() {
 94         return bodAmount;
 95     }
 96 
 97     public void setBodAmount(Integer bodAmount) {
 98         this.bodAmount = bodAmount;
 99     }
100 
101     public BigDecimal getBodBuyPrice() {
102         return bodBuyPrice;
103     }
104 
105     public void setBodBuyPrice(BigDecimal bodBuyPrice) {
106         this.bodBuyPrice = bodBuyPrice;
107     }
108 
109   
110 
111     public BigDecimal getBodTotalPrice() {
112         return bodTotalPrice;
113     }
114 
115     public void setBodTotalPrice(BigDecimal bodTotalPrice) {
116         this.bodTotalPrice = bodTotalPrice;
117     }
118 
119     public String getBoId() {
120         return boId;
121     }
122 
123     public void setBoId(String boId) {
124         this.boId = boId == null ? null : boId.trim();
125     }
126 
127     public String getBodImeiList() {
128         return bodImeiList;
129     }
130 
131     public void setBodImeiList(String bodImeiList) {
132         this.bodImeiList = bodImeiList == null ? null : bodImeiList.trim();
133     }
134 }
View Code

  Birthday.java

技术分享
 1 package cn.hp.testjson;
 2 
 3 public class Birthday {
 4 private String birthday;
 5     
 6     public Birthday(String birthday) {
 7         super();
 8         this.birthday = birthday;
 9     }
10 
11     //getter、setter
12 
13     public Birthday() {}
14     
15     @Override
16     public String toString() {
17         return this.birthday;
18     }
19 }
View Code

     AccountBean.java

技术分享
 1 package cn.hp.testjson;
 2 
 3 public class AccountBean {
 4     private int id;
 5     private String name;
 6     private String email;
 7     private String address;
 8     private Birthday birthday;
 9     
10     //getter、setter
11     
12     @Override
13     public String toString() {
14         return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
15     }
16 
17     public int getId() {
18         return id;
19     }
20 
21     public void setId(int id) {
22         this.id = id;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public String getEmail() {
34         return email;
35     }
36 
37     public void setEmail(String email) {
38         this.email = email;
39     }
40 
41     public String getAddress() {
42         return address;
43     }
44 
45     public void setAddress(String address) {
46         this.address = address;
47     }
48 
49     public Birthday getBirthday() {
50         return birthday;
51     }
52 
53     public void setBirthday(Birthday birthday) {
54         this.birthday = birthday;
55     }
56 }
View Code

主要用于测试json可以将一个对象,数组,集合,map等转换为json格式的字符串。

           将正确的json格式字符串转换为对象,数组,集合,map等。

技术分享
  1 package cn.hp.testjson;
  2 
  3 import java.io.IOException;
  4 import java.util.ArrayList;
  5 import java.util.HashMap;
  6 import java.util.Iterator;
  7 import java.util.LinkedHashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 import java.util.Set;
 11 
 12 import org.codehaus.jackson.JsonEncoding;
 13 import org.codehaus.jackson.JsonGenerator;
 14 import org.codehaus.jackson.JsonParseException;
 15 import org.codehaus.jackson.map.JsonMappingException;
 16 import org.codehaus.jackson.map.ObjectMapper;
 17 import org.junit.After;
 18 import org.junit.Before;
 19 import org.junit.Test;
 20 
 21 public class JacksonTest {
 22     private JsonGenerator jsonGenerator = null;
 23     private ObjectMapper objectMapper = null;
 24     private AccountBean bean = null;
 25 
 26     @Before
 27     public void init() {
 28         bean = new AccountBean();
 29         bean.setAddress("china-Guangzhou");
 30         bean.setEmail("[email protected]");
 31         bean.setId(1);
 32         bean.setName("hoojo");
 33 
 34         objectMapper = new ObjectMapper();
 35         try {
 36             jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
 37                     System.out, JsonEncoding.UTF8);
 38         } catch (IOException e) {
 39             e.printStackTrace();
 40         }
 41     }
 42 
 43     @After
 44     public void destory() {
 45         try {
 46             if (jsonGenerator != null) {
 47                 jsonGenerator.flush();
 48             }
 49             if (!jsonGenerator.isClosed()) {
 50                 jsonGenerator.close();
 51             }
 52             jsonGenerator = null;
 53             objectMapper = null;
 54             bean = null;
 55             System.gc();
 56         } catch (IOException e) {
 57             e.printStackTrace();
 58         }
 59     }
 60 
 61     /**
 62      * <b>function:</b>将java对象转换成json字符串
 63      */
 64     @Test
 65     public void writeEntityJSON() {
 66 
 67         try {
 68             System.out.println("jsonGenerator");
 69             // writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
 70             jsonGenerator.writeObject(bean);
 71             System.out.println();
 72 
 73             System.out.println("ObjectMapper");
 74             // writeValue具有和writeObject相同的功能
 75             objectMapper.writeValue(System.out, bean);
 76             
 77         } catch (IOException e) {
 78             e.printStackTrace();
 79         }
 80     }
 81 
 82     /**
 83      * <b>function:</b>将map转换成json字符串
 84      */
 85     @Test
 86     public void writeMapJSON() {
 87         try {
 88             Map<String, Object> map = new HashMap<String, Object>();
 89             map.put("name", bean.getName());
 90             map.put("account", bean);
 91             bean = new AccountBean();
 92             bean.setAddress("china-Beijin");
 93             bean.setEmail("[email protected]");
 94             map.put("account2", bean);
 95 
 96             System.out.println("jsonGenerator");
 97             jsonGenerator.writeObject(map);
 98             System.out.println("");
 99 
100             System.out.println("objectMapper");
101             
102             objectMapper.writeValue(System.out, map);
103         } catch (IOException e) {
104             e.printStackTrace();
105         }
106     }
107 
108     /**
109      * <b>function:</b>将list集合转换成json字符串
110      */
111     @Test
112     public void writeListJSON() {
113         try {
114             List<AccountBean> list = new ArrayList<AccountBean>();
115             list.add(bean);
116 
117             bean = new AccountBean();
118             bean.setId(2);
119             bean.setAddress("address2");
120             bean.setEmail("email2");
121             bean.setName("haha2");
122             list.add(bean);
123 
124             System.out.println("jsonGenerator");
125             // list转换成JSON字符串
126             jsonGenerator.writeObject(list);
127             
128             System.out.println();
129             System.out.println("ObjectMapper");
130             // 用objectMapper直接返回list转换成的JSON字符串
131             System.out.println("1###" + objectMapper.writeValueAsString(list));
132             System.out.print("2###");
133             // objectMapper list转换成JSON字符串
134             objectMapper.writeValue(System.out, list);
135         } catch (IOException e) {
136             e.printStackTrace();
137         }
138     }
139 
140     @Test
141     public void readJson2Entity() {
142         String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
143         try {
144             AccountBean acc = objectMapper.readValue(json, AccountBean.class);
145             System.out.println(acc.getName());
146             System.out.println(acc);
147         } catch (JsonParseException e) {
148             e.printStackTrace();
149         } catch (JsonMappingException e) {
150             e.printStackTrace();
151         } catch (IOException e) {
152             e.printStackTrace();
153         }
154     }
155 
156     /**
157      * <b>function:</b>json字符串转换成list<map>
158      */
159     @Test
160     public void readJson2List() {
161         String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
162         try {
163             List<LinkedHashMap<String, Object>> list = objectMapper.readValue(
164                     json, List.class);
165             System.out.println(list.size());
166             for (int i = 0; i < list.size(); i++) {
167                 Map<String, Object> map = list.get(i);
168                 Set<String> set = map.keySet();
169                 for (Iterator<String> it = set.iterator(); it.hasNext();) {
170                     String key = it.next();
171                     System.out.println(key + ":" + map.get(key));
172                 }
173             }
174         } catch (JsonParseException e) {
175             e.printStackTrace();
176         } catch (JsonMappingException e) {
177             e.printStackTrace();
178         } catch (IOException e) {
179             e.printStackTrace();
180         }
181     }
182 
183     /**
184      * <b>function:</b>json字符串转换成Array
185      * 
186      */
187     @Test
188     public void readJson2Array() {
189         String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
190         try {
191             AccountBean[] arr = objectMapper.readValue(json,
192                     AccountBean[].class);
193             System.out.println(arr.length);
194             for (int i = 0; i < arr.length; i++) {
195                 System.out.println(arr[i]);
196             }
197 
198         } catch (JsonParseException e) {
199             e.printStackTrace();
200         } catch (JsonMappingException e) {
201             e.printStackTrace();
202         } catch (IOException e) {
203             e.printStackTrace();
204         }
205     }
206 
207     /**
208      * <b>function:</b>json字符串转换成Array
209      * 
210      */
211     @Test
212     public void myReadJson2Array() {
213         String json = "    [{\"goodsId\":\"10\",\"goodsName\":\"苹果4\"},{\"goodsId\":\"2\",\"goodsName\":\"note2\"}]";
214         try {
215             BuyOrderDetail[] arr = objectMapper.readValue(json, BuyOrderDetail[].class);
216             System.out.println(arr.length);
217             for (int i = 0; i < arr.length; i++) {
218                 System.out.println(arr[i]);
219             }
220             
221         } catch (JsonParseException e) {
222             e.printStackTrace();
223         } catch (JsonMappingException e) {
224             e.printStackTrace();
225         } catch (IOException e) {
226             e.printStackTrace();
227         }
228     }
229 
230 }
View Code

技术分享

多种格式的嵌套

技术分享

 

以上是关于json篇的主要内容,如果未能解决你的问题,请参考以下文章

json 可视代码工作室Angular with Firebase片段

vs code 用户代码片段 html.json

错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”

配置 VScode 编辑器 (前端篇)

如何在android中将json数据加载到片段中

使用 json rereiver php mysql 在片段中填充列表视图