-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
838 lines (428 loc) · 57.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
<!doctype html>
<html class="theme-next muse use-motion" lang="">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />
<meta name="keywords" content="Hexo, NexT" />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />
<meta property="og:type" content="website">
<meta property="og:title" content="易凡的技术园地">
<meta property="og:url" content="https://efan006.github.io/index.html">
<meta property="og:site_name" content="易凡的技术园地">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="易凡的技术园地">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Muse',
sidebar: {"position":"left","display":"post"},
fancybox: true,
motion: true,
duoshuo: {
userId: '0',
author: 'Author'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="https://efan006.github.io/"/>
<title> 易凡的技术园地 </title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="">
<div class="container one-collumn sidebar-position-left
page-home
">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">易凡的技术园地</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">时间无言,却证明一切</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
Startseite
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
Archiv
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
Tags
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-expand">
<article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
<link itemprop="mainEntityOfPage" href="https://efan006.github.io/2016/11/23/一篇搞定Java序列化/">
<span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="efan">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="易凡的技术园地">
<span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
<img style="display:none;" itemprop="url image" alt="易凡的技术园地" src="">
</span>
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2016/11/23/一篇搞定Java序列化/" itemprop="url">
一篇搞定Java序列化
</a>
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">Veröffentlicht am</span>
<time title="Post created" itemprop="dateCreated datePublished" datetime="2016-11-23T15:35:44+08:00">
2016-11-23
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<!-- toc -->
<ul>
<li><a href="#序列化">序列化</a></li>
<li><a href="#serializable">Serializable</a><ul>
<li><a href="#用法">用法</a></li>
<li><a href="#使用细节">使用细节</a></li>
</ul>
</li>
<li><a href="#parcelable">Parcelable</a><ul>
<li><a href="#特点">特点</a></li>
<li><a href="#用法-1">用法</a></li>
</ul>
</li>
<li><a href="#xmlextensible-markup-language">XML(eXtensible Markup Language)</a><ul>
<li><a href="#特点-1">特点</a></li>
<li><a href="#用法-2">用法</a></li>
<li><a href="#使用细节-1">使用细节</a></li>
</ul>
</li>
<li><a href="#jsonjavascript-object-notation">JSON(JavaScript Object Notation)</a><ul>
<li><a href="#特点-2">特点</a></li>
<li><a href="#fastjson-使用细节">fastjson 使用细节</a></li>
<li><a href="#各种json库的比较on-android">各种JSON库的比较(on Android)</a></li>
</ul>
</li>
<li><a href="#protobufgoogle-protocol-buffers">Protobuf(Google Protocol Buffers)</a><ul>
<li><a href="#特点-3">特点</a></li>
<li><a href="#用法-3">用法</a><ul>
<li><a href="#写proto文件定义数据结构">写proto文件定义数据结构</a></li>
<li><a href="#生成java文件">生成java文件</a></li>
<li><a href="#导入jar包">导入jar包</a></li>
</ul>
</li>
<li><a href="#注意事项">注意事项</a></li>
<li><a href="#另一种选择">另一种选择</a></li>
</ul>
</li>
</ul>
<!-- tocstop -->
<h1 id="序列化"><a href="#序列化" class="headerlink" title="序列化"></a>序列化</h1><p>可以理解为一种数据对象和二进制串的转化协议,用于数据持久化和数据传输</p>
<h1 id="serializable"><a href="#Serializable" class="headerlink" title="Serializable"></a>Serializable</h1><h2 id="用法"><a href="#用法" class="headerlink" title="用法"></a>用法</h2><ol>
<li>数据对象实现java.io.Serializable,否则会抛出NotSerializableException</li>
<li>通过ObjectOutputStream和ObjectInputStream对对象进行序列化和反序列化</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> <T> <span class="function"><span class="keyword">void</span> <span class="title">write</span><span class="params">(OutputStream output, T bean)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> ObjectOutputStream oos = <span class="keyword">null</span>;</div><div class="line"> <span class="keyword">try</span> {</div><div class="line"> oos = <span class="keyword">new</span> ObjectOutputStream(output);</div><div class="line"> oos.writeObject(bean);</div><div class="line"> } <span class="keyword">catch</span> (IOException e) {</div><div class="line"> e.printStackTrace();</div><div class="line"> } <span class="keyword">finally</span> {</div><div class="line"> IOUtils.closeQuietly(oos);</div><div class="line"> }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="keyword">public</span> <T> <span class="function">T <span class="title">read</span><span class="params">(InputStream input, Class<T> entityClass)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> ObjectInputStream ois = <span class="keyword">null</span>;</div><div class="line"> <span class="keyword">try</span> {</div><div class="line"> ois = <span class="keyword">new</span> ObjectInputStream(input);</div><div class="line"> <span class="keyword">return</span> (T) ois.readObject();</div><div class="line"> } <span class="keyword">catch</span> (IOException | ClassNotFoundException e) {</div><div class="line"> e.printStackTrace();</div><div class="line"> <span class="keyword">return</span> <span class="keyword">null</span>;</div><div class="line"> } <span class="keyword">finally</span> {</div><div class="line"> IOUtils.closeQuietly(ois);</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure>
<h2 id="使用细节"><a href="#使用细节" class="headerlink" title="使用细节"></a>使用细节</h2><ol>
<li>transient关键字修饰的变量,可以阻止序列化该变量。反序列化时,transient 变量会被赋值为初始值</li>
<li>在类中增加writeObject 和 readObject 方法可以实现自定义序列化策略<ul>
<li>ArrayList内部就是将元素transient了,然后自定义writeObject和readObject方法,因为ArrayList是动态数组,这样做可以避免大量空对象被序列化</li>
<li>加解密密数据可以在writeObject 和 readObject 中实现</li>
</ul>
</li>
<li>序列化不关注静态变量</li>
<li>父类不实现Serializable的话那么父类的变量不会被序列化</li>
<li>serialVersionUID一致时两个相同的类才能被序列化成功,没有特殊情况都用固定的1L即可<ul>
<li>特性案例:Server端重新生成serialVersionUID,可以导致Client端反序列化失败,强制客户端升级</li>
</ul>
</li>
<li><p>序列化会破坏单例模式</p>
<ul>
<li><p>要么用静态内部类的方式写单例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>{</div><div class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Holder</span> </span>{</div><div class="line"> <span class="keyword">private</span> <span class="keyword">static</span> Singleton singleton = <span class="keyword">new</span> Singleton();</div><div class="line"> }</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span><span class="params">()</span></span>{}</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getSingleton</span><span class="params">()</span></span>{</div><div class="line"> <span class="keyword">return</span> Holder.singleton;</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure>
</li>
<li><p>要么单例对象重写readReslove方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>{</div><div class="line"> <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> Singleton singleton;</div><div class="line"> <span class="function"><span class="keyword">private</span> <span class="title">Singleton</span> <span class="params">()</span></span>{}</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Singleton <span class="title">getSingleton</span><span class="params">()</span> </span>{</div><div class="line"> <span class="keyword">if</span> (singleton == <span class="keyword">null</span>) {</div><div class="line"> <span class="keyword">synchronized</span> (Singleton.class) {</div><div class="line"> <span class="keyword">if</span> (singleton == <span class="keyword">null</span>) {</div><div class="line"> singleton = <span class="keyword">new</span> Singleton();</div><div class="line"> }</div><div class="line"> }</div><div class="line"> }</div><div class="line"> <span class="keyword">return</span> singleton;</div><div class="line"> }</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">private</span> Object <span class="title">readResolve</span><span class="params">()</span> </span>{</div><div class="line"> <span class="keyword">return</span> singleton;</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ol>
<h1 id="parcelable"><a href="#Parcelable" class="headerlink" title="Parcelable"></a>Parcelable</h1><h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><p>Android特有,比Serializable高效,节省内存,可用于Intent传递和IPC,但不推荐用于持久化,因为存在版本差异</p>
<h2 id="用法"><a href="#用法-1" class="headerlink" title="用法"></a>用法</h2><ol>
<li>实现Parcelable</li>
<li>重写writeToParcel和Parcelable.Creator里的createFromParcel方法,注意顺序一定要一致</li>
</ol>
<h1 id="xmlextensible-markup-language"><a href="#XML(eXtensible-Markup-Language)" class="headerlink" title="XML(eXtensible Markup Language)"></a>XML(eXtensible Markup Language)</h1><h2 id="特点"><a href="#特点-1" class="headerlink" title="特点"></a>特点</h2><ol>
<li>XML被设计为传输和存储数据,W3C标准</li>
<li>具有自我描述性,但仅仅是纯文本,不会处理任何事情 </li>
</ol>
<h2 id="用法"><a href="#用法-2" class="headerlink" title="用法"></a>用法</h2><ol>
<li>基于事件驱动的SAX、Pull方式,内存占用少,使用比较复杂,还有把XML全部加载成树结构的DOM方式,使用灵活但内存占用多</li>
<li>我比较懒,直接用了Square Retrofit里的XML解析器-SimpleXML,使用就像JSON一样简单<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XmlConverter</span> <span class="keyword">implements</span> <span class="title">IConverter</span> </span>{</div><div class="line"> </div><div class="line"> <span class="keyword">private</span> <span class="keyword">final</span> Serializer serializer = <span class="keyword">new</span> Persister();</div><div class="line"> </div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="keyword">public</span> <T> <span class="function">String <span class="title">toString</span><span class="params">(T bean)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> ByteArrayOutputStream output = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line"> write(output, bean);</div><div class="line"> <span class="keyword">return</span> output.toString();</div><div class="line"> }</div><div class="line"> </div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="keyword">public</span> <T> <span class="function">T <span class="title">toBean</span><span class="params">(String string, Class<T> entityClass)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> <span class="keyword">if</span> (entityClass == String.class</div><div class="line"> || entityClass == CharSequence.class){</div><div class="line"> <span class="keyword">return</span> (T)string;</div><div class="line"> } <span class="keyword">else</span> <span class="keyword">if</span> (entityClass == <span class="keyword">char</span>[].class){</div><div class="line"> <span class="keyword">return</span> (T)string.toCharArray();</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="keyword">return</span> serializer.read(entityClass, string);</div><div class="line"> }</div><div class="line"> }</div><div class="line"> </div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="keyword">public</span> <T> <span class="function"><span class="keyword">void</span> <span class="title">write</span><span class="params">(OutputStream output, T bean)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> serializer.write(bean, output);</div><div class="line"> }</div><div class="line"> </div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="keyword">public</span> <T> <span class="function">T <span class="title">read</span><span class="params">(InputStream input, Class<T> entityClass)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> <span class="keyword">return</span> serializer.read(entityClass, input);</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="使用细节"><a href="#使用细节-1" class="headerlink" title="使用细节"></a>使用细节</h2><p>某些文本,比如 JavaScript 代码,包含大量 “<” 或 “&” 字符。为了避免错误,可以将脚本代码定义为 CDATA。CDATA 部分中的所有内容都会被解析器忽略。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">//CDATA 由 <![CDATA[ 开始,由 ]]> 结束</div><div class="line">//以下五种符号需要做转义</div><div class="line">&lt; < 小于</div><div class="line">&gt; > 大于</div><div class="line">&amp; & 和号</div><div class="line">&apos; ' 省略号</div><div class="line">&quot; " 引号</div></pre></td></tr></table></figure></p>
<h1 id="jsonjavascript-object-notation"><a href="#JSON(JavaScript-Object-Notation)" class="headerlink" title="JSON(JavaScript Object Notation)"></a>JSON(JavaScript Object Notation)</h1><h2 id="特点"><a href="#特点-2" class="headerlink" title="特点"></a>特点</h2><ol>
<li>用“属性-值”的方式来描述对象,保持了人眼可读的优点</li>
<li>相比XML数据更加简洁(文件大小将近一半),解析更快</li>
<li>JS的先天支持,广泛应用于web browser场景中,有良好的扩展性和兼容性</li>
</ol>
<h2 id="fastjson-使用细节"><a href="#fastjson-使用细节" class="headerlink" title="fastjson 使用细节"></a>fastjson 使用细节</h2><ol>
<li>要有默认构造方法,或者有@JSONCreator的构造方法,不然会报JSONException</li>
<li>要有成员要public或者要有get/set方法(我们工程约定统一用get/set方法),不然解析不到</li>
<li>用@JSONField(name=”xxx”)指定key名字,不指定的话采用变量名,可能会被代码混淆导致解析错误</li>
<li>用@JSONField(format=”yyyyMMdd”)配置日期格式</li>
<li>有些场景属性互相依赖,需要在构造方法中做初始化,可以使用@JSONCreator来指定构造函数<ul>
<li>@JSONCreator只能有一个</li>
<li>参数必须添加注解@JSONField(name=”xxx”)</li>
<li>子类的@JSONCreator不会继承父类的@JSONCreator</li>
</ul>
</li>
<li>有些场景属性相互依赖,需要在bean反序列化后对数据做二次处理,可以使类实现JavaBeanDeserializerListener,在onDeserializerSuccess做二次处理</li>
<li>序列化默认跳过null,如果需要序列化,可以再序列化方法里传SerializerFeature WriteMapNullValue:是否输出值为null的字段,默认为false<br>还有其他feature:<ul>
<li>QuoteFieldNames 输出key时是否使用双引号,默认为true </li>
<li>WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null </li>
<li>WriteNullListAsEmpty List字段如果为null,输出为[],而非null </li>
<li>WriteNullStringAsEmpty 字符类型字段如果为null,输出为””,而非null </li>
<li>WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null </li>
</ul>
</li>
<li>顺序问题<ul>
<li>数组和List不会乱序</li>
<li>在1.1.26版本 JSONObject和Bean序列化后会乱序,</li>
<li>在1.1.41会按key的顺序重新排序,</li>
<li>在1.1.42之后可以通过@JSONField(ordinal = 1)指定顺序</li>
<li>还可以在类上配置@JSONType(orders = {})来设置顺序</li>
</ul>
</li>
<li>反序列化遇到重复的key,以后面的为准</li>
</ol>
<h2 id="各种json库的比较on-android"><a href="#各种JSON库的比较(on-Android)" class="headerlink" title="各种JSON库的比较(on Android)"></a>各种JSON库的比较(on Android)</h2><ul>
<li>依赖比较: fastjson(202K) < gson(226K) < jackson(33+190+828=1051K)</li>
<li>流行度: gson > fastjson > jackson //p.s. fastjson仅在中国流行</li>
<li>速度比较:小数据量上fastjson和gson差不多,优于jackson;大数据量上,fastjson和jackson差不多,gson很差<ul>
<li>p.s. fastjson在jvm平台上的性能比在Android上优秀,因为运用了ASM库</li>
</ul>
</li>
<li>用法比较:<ul>
<li>fastjson:<ol>
<li>对构造方法、get/set方法的规范比较多(见上文),不留神容易遇到坑</li>
<li>旧版本bug比较多,最好使用最新版 </li>
</ol>
</li>
<li>gson:<ol>
<li>类型不对不报错,直接返回默认值</li>
<li>默认不序列化null,如果需要序列化:Gson gson = new GsonBuilder().serializeNulls().create(); </li>
<li>如果需要反序列化null为””,需要注册TypeAdapter,如果需要反序列化null为空list,需要添加@JsonAdapter注解(可参考我针对这个写的一篇<a href="http://blog.csdn.net/efan006/article/details/50544509" target="_blank" rel="external">博客日志</a>)</li>
</ol>
</li>
<li>jackson:序列化默认不会跳过null,如果需要跳过<ul>
<li>可以在数据对象上使用@JsonInclude(Include.NON_NULL)</li>
<li>也可以在序列化方法上mapper.setSerializationInclusion(Include.NON_NULL); </li>
</ul>
</li>
</ul>
</li>
</ul>
<h1 id="protobufgoogle-protocol-buffers"><a href="#Protobuf(Google-Protocol-Buffers)" class="headerlink" title="Protobuf(Google Protocol Buffers)"></a>Protobuf(Google Protocol Buffers)</h1><h2 id="特点"><a href="#特点-3" class="headerlink" title="特点"></a>特点</h2><ol>
<li>Google开发的一种轻便高效的数据存储格式, 适合内部对性能要求高的RPC调用</li>
<li>特点是二进制格式,数据量小(相当于json的40%左右),解包速度快,非常适合数据存储或交换</li>
<li>proto2仅支持Java,C++,Python三种语言, proto3还支持JavaScript, Objective-C, Ruby, C#, Go.</li>
</ol>
<h2 id="用法"><a href="#用法-3" class="headerlink" title="用法"></a>用法</h2><h3 id="写proto文件定义数据结构"><a href="#写proto文件定义数据结构" class="headerlink" title="写proto文件定义数据结构"></a>写proto文件定义数据结构</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line">//可以写注释,会自动转到java类里</div><div class="line"></div><div class="line">import "xxx.proto" //import表示依赖其他proto文件</div><div class="line">option java_package = "com.fs.fsprobuf"; //java_package 代表这个文件所在的包名</div><div class="line">option java_outer_classname = "User"; //java_outer_classname 即为类名</div><div class="line"></div><div class="line">message Person { //message代表一个类</div><div class="line"> </div><div class="line"> enum PhoneType{ //enum是一个枚举类型</div><div class="line"> MOBILE = 0; </div><div class="line"> HOME = 1;</div><div class="line"> WORK = 2;</div><div class="line"> }</div><div class="line"></div><div class="line"> message PhoneNumber{</div><div class="line"> required string number = 1; //required 代表该字段必填,没传值会报错</div><div class="line"> optional PhoneType type = 2[default = HOME] //optional 代表该字段可选,并可以为其设置默认值,默认值格式[defalut=]。</div><div class="line"> }</div><div class="line"></div><div class="line"> required int32 id = 2; //整型int32 布尔值bool</div><div class="line"> required string name = 1; //required int32 userId = 1 (修饰词 类型 域名 = 标记值)这是一个域 </div><div class="line"> optional string email = 3[default="123"]; //标记值是用来在二进制编码里唯一确认当前域的</div><div class="line"> repeated PhoneNumber phone = 4; //repeated 代表一个list</div><div class="line">}</div></pre></td></tr></table></figure>
<h3 id="生成java文件"><a href="#生成java文件" class="headerlink" title="生成java文件"></a>生成java文件</h3><p>使用官方工具把proto文件编译成java文件,放到工程里与package对应的路径下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">protoc-java.exe --java_out=./ *.proto</div></pre></td></tr></table></figure></p>
<h3 id="导入jar包"><a href="#导入jar包" class="headerlink" title="导入jar包"></a>导入jar包</h3><p>下载官方的protobuf-java的jar包引入到工程里,使用工具类进行数据读写<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@overide</span></div><div class="line"><span class="keyword">public</span> <T> <span class="function"><span class="keyword">void</span> <span class="title">write</span><span class="params">(OutputStream output, T bean)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> <span class="keyword">if</span> (bean <span class="keyword">instanceof</span> MessageLite){</div><div class="line"> ((MessageLite)bean).writeTo(output);</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(bean.getClass().getName() + <span class="string">"is not a protobuf message"</span>);</div><div class="line"> }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="meta">@overide</span></div><div class="line"><span class="keyword">public</span> <T> <span class="function">T <span class="title">read</span><span class="params">(InputStream input, Class<T> entityClass)</span> <span class="keyword">throws</span> Exception </span>{</div><div class="line"> <span class="keyword">if</span> (MessageLite.class.isAssignableFrom(entityClass)) {</div><div class="line"> Parser<MessageLite> parser;</div><div class="line"> <span class="keyword">try</span> {</div><div class="line"> Field field = entityClass.getDeclaredField(<span class="string">"PARSER"</span>);</div><div class="line"> parser = (Parser<MessageLite>) field.get(<span class="keyword">null</span>);</div><div class="line"> <span class="keyword">return</span> (T)parser.parseFrom(input);</div><div class="line"> } <span class="keyword">catch</span> (NoSuchFieldException | IllegalAccessException e) {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</div><div class="line"> <span class="string">"Found a protobuf message but "</span> + entityClass.getName() + <span class="string">" had no PARSER field."</span>);</div><div class="line"> }</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(entityClass.getName() + <span class="string">"is not a protobuf message"</span>);</div><div class="line"> }</div><div class="line">}</div></pre></td></tr></table></figure></p>
<h2 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h2><ol>
<li>升级proto定义,不可修改现有域的标记值,不可添加/删除required域。可以删除optional,repeated域。添加optional,repeated域必须采用不同的标记值(之前删除过的也不能用)</li>
<li>proto文件转成的java类 带有大量的方法(实测仅3个变量的类,生成了近100个方法,800行代码)。这在Android上极易导致方法数超65535上限</li>
</ol>
<h2 id="另一种选择"><a href="#另一种选择" class="headerlink" title="另一种选择"></a>另一种选择</h2><p>我们也可以采用Square Wire 项目的proto工具 </p>
<ol>
<li>首先也是写proto文件,一样的 </li>
<li>在项目gradle里引入wire组件<figure class="highlight gradle"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">compile</span> <span class="string">'com.squareup.wire:wire-runtime:2.2.0'</span> </div><div class="line">``` </div><div class="line"><span class="number">3</span>. 然后下载wire-compiler-VERSION-jar-with-<span class="keyword">dependencies</span>.jar工具,这个需要去maven仓库下载[下载地址](http:<span class="comment">//search.maven.org/#search|ga|1|g%3A%22com.squareup.wire%22) 注意要选择与gradle引入的wire版本一致</span></div><div class="line"><span class="number">4</span>. 使用cmd执行命令生成java文件 </div><div class="line">``` </div><div class="line">java -jar -Dfile.encoding=UTF-<span class="number">8</span> wire-compiler-<span class="number">2.2</span>.<span class="number">0</span>-jar-with-<span class="keyword">dependencies</span>.jar --proto_path=. --java_out=. *.proto </div><div class="line">``` </div><div class="line"><span class="number">5</span>. 使用工具类读写</div><div class="line">``` java</div><div class="line"> @Override</div><div class="line"> <span class="keyword">public</span> <T> <span class="keyword">void</span> <span class="keyword">write</span>(OutputStream output, T bean) <span class="keyword">throws</span> Exception {</div><div class="line"> <span class="keyword">if</span> (bean <span class="keyword">instanceof</span> Message){</div><div class="line"> ((Message)bean).encode(output);</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(bean.getClass().getName() + <span class="string">" is not a protobuf message"</span>);</div><div class="line"> }</div><div class="line"> }</div><div class="line"> </div><div class="line"> @Override</div><div class="line"> <span class="keyword">public</span> <T> T <span class="keyword">read</span>(InputStream input, <span class="keyword">Class</span><T> entityClass) <span class="keyword">throws</span> Exception {</div><div class="line"> <span class="keyword">if</span> (Message.<span class="keyword">class</span>.isAssignableFrom(entityClass)) {</div><div class="line"> ProtoAdapter<Message> adapter;</div><div class="line"> <span class="keyword">try</span> {</div><div class="line"> Field field = entityClass.getDeclaredField(<span class="string">"ADAPTER"</span>);</div><div class="line"> adapter = (ProtoAdapter<Message>)field.get(<span class="keyword">null</span>);</div><div class="line"> <span class="keyword">return</span> (T)adapter.decode(input);</div><div class="line"> } <span class="keyword">catch</span> (NoSuchFieldException | IllegalAccessException e) {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</div><div class="line"> <span class="string">"Found a protobuf message but "</span> + entityClass.getName() + <span class="string">" had no ADAPTER field."</span>);</div><div class="line"> }</div><div class="line"> } <span class="keyword">else</span> {</div><div class="line"> <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(entityClass.getName() + <span class="string">" is not a protobuf message"</span>);</div><div class="line"> }</div><div class="line"> }</div></pre></td></tr></table></figure>
</li>
</ol>
<p>使用wire项目的工具,方法数显著裁剪了(还是之前3个变量的类,方法20多个,188行代码)</p>
</div>
<div>
</div>
<div>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</article>
<article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
<link itemprop="mainEntityOfPage" href="https://efan006.github.io/2016/11/23/hello-world/">
<span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="efan">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="易凡的技术园地">
<span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
<img style="display:none;" itemprop="url image" alt="易凡的技术园地" src="">
</span>
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2016/11/23/hello-world/" itemprop="url">
Hello World
</a>
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">Veröffentlicht am</span>
<time title="Post created" itemprop="dateCreated datePublished" datetime="2016-11-23T15:06:07+08:00">
2016-11-23
</time>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>Welcome to <a href="https://hexo.io/" target="_blank" rel="external">Hexo</a>! This is your very first post. Check <a href="https://hexo.io/docs/" target="_blank" rel="external">documentation</a> for more info. If you get any problems when using Hexo, you can find the answer in <a href="https://hexo.io/docs/troubleshooting.html" target="_blank" rel="external">troubleshooting</a> or you can ask me on <a href="https://github.com/hexojs/hexo/issues" target="_blank" rel="external">GitHub</a>.</p>
<h2 id="quick-start"><a href="#Quick-Start" class="headerlink" title="Quick Start"></a>Quick Start</h2><h3 id="create-a-new-post"><a href="#Create-a-new-post" class="headerlink" title="Create a new post"></a>Create a new post</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo new <span class="string">"My New Post"</span></div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/writing.html" target="_blank" rel="external">Writing</a></p>
<h3 id="run-server"><a href="#Run-server" class="headerlink" title="Run server"></a>Run server</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo server</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/server.html" target="_blank" rel="external">Server</a></p>
<h3 id="generate-static-files"><a href="#Generate-static-files" class="headerlink" title="Generate static files"></a>Generate static files</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo generate</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/generating.html" target="_blank" rel="external">Generating</a></p>
<h3 id="deploy-to-remote-sites"><a href="#Deploy-to-remote-sites" class="headerlink" title="Deploy to remote sites"></a>Deploy to remote sites</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ hexo deploy</div></pre></td></tr></table></figure>
<p>More info: <a href="https://hexo.io/docs/deployment.html" target="_blank" rel="external">Deployment</a></p>
</div>
<div>
</div>
<div>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</article>
</section>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview sidebar-panel sidebar-panel-active">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="/images/avatar.gif"
alt="efan" />
<p class="site-author-name" itemprop="name">efan</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">2</span>
<span class="site-state-item-name">Artikel</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright" >
©
<span itemprop="copyrightYear">2016</span>
<span class="with-love">
<i class="fa fa-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">efan</span>
</div>
<div class="powered-by">
Erstellt mit <a class="theme-link" href="https://hexo.io">Hexo</a>
</div>
<div class="theme-info">
Theme -
<a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
NexT.Muse
</a>
</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>
</body>
</html>