-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
JSON.java
1425 lines (1201 loc) · 49.8 KB
/
JSON.java
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.*;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider;
import com.alibaba.fastjson.parser.deserializer.FieldTypeResolver;
import com.alibaba.fastjson.parser.deserializer.ParseProcess;
import com.alibaba.fastjson.serializer.*;
import com.alibaba.fastjson.util.IOUtils;
import com.alibaba.fastjson.util.TypeUtils;
/**
* This is the main class for using Fastjson. You usually call these two methods {@link #toJSONString(Object)} and {@link #parseObject(String, Class)}.
*
* <p>Here is an example of how fastjson is used for a simple Class:
*
* <pre>
* Model model = new Model();
* String json = JSON.toJSONString(model); // serializes model to Json
* Model model2 = JSON.parseObject(json, Model.class); // deserializes json into model2
* </pre>
*
* <p>If the object that your are serializing/deserializing is a {@code ParameterizedType}
* (i.e. contains at least one type parameter and may be an array) then you must use the
* {@link #toJSONString(Object)} or {@link #parseObject(String, Type, Feature[])} method. Here is an
* example for serializing and deserialing a {@code ParameterizedType}:
*
* <pre>
* String json = "[{},...]";
* Type listType = new TypeReference<List<Model>>() {}.getType();
* List<Model> modelList = JSON.parseObject(json, listType);
* </pre>
*
* @see com.alibaba.fastjson.TypeReference
*
* @author wenshao[szujobs@hotmail.com]
*/
public abstract class JSON implements JSONStreamAware, JSONAware {
public static TimeZone defaultTimeZone = TimeZone.getDefault();
public static Locale defaultLocale = Locale.getDefault();
public static String DEFAULT_TYPE_KEY = "@type";
static final SerializeFilter[] emptyFilters = new SerializeFilter[0];
public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static int DEFAULT_PARSER_FEATURE;
public static int DEFAULT_GENERATE_FEATURE;
private static final ConcurrentHashMap<Type, Type> mixInsMapper = new ConcurrentHashMap<Type, Type>(16);
static {
int features = 0;
features |= Feature.AutoCloseSource.getMask();
features |= Feature.InternFieldNames.getMask();
features |= Feature.UseBigDecimal.getMask();
features |= Feature.AllowUnQuotedFieldNames.getMask();
features |= Feature.AllowSingleQuotes.getMask();
features |= Feature.AllowArbitraryCommas.getMask();
features |= Feature.SortFeidFastMatch.getMask();
features |= Feature.IgnoreNotMatch.getMask();
DEFAULT_PARSER_FEATURE = features;
}
static {
int features = 0;
features |= SerializerFeature.QuoteFieldNames.getMask();
features |= SerializerFeature.SkipTransientField.getMask();
features |= SerializerFeature.WriteEnumUsingName.getMask();
features |= SerializerFeature.SortField.getMask();
DEFAULT_GENERATE_FEATURE = features;
config(IOUtils.DEFAULT_PROPERTIES);
}
private static void config(Properties properties) {
{
String featuresProperty = properties.getProperty("fastjson.serializerFeatures.MapSortField");
int mask = SerializerFeature.MapSortField.getMask();
if ("true".equals(featuresProperty)) {
DEFAULT_GENERATE_FEATURE |= mask;
} else if ("false".equals(featuresProperty)) {
DEFAULT_GENERATE_FEATURE &= ~mask;
}
}
{
if ("true".equals(properties.getProperty("parser.features.NonStringKeyAsString"))) {
DEFAULT_PARSER_FEATURE |= Feature.NonStringKeyAsString.getMask();
}
}
{
if ("true".equals(properties.getProperty("parser.features.ErrorOnEnumNotMatch"))
|| "true".equals(properties.getProperty("fastjson.parser.features.ErrorOnEnumNotMatch")))
{
DEFAULT_PARSER_FEATURE |= Feature.ErrorOnEnumNotMatch.getMask();
}
}
{
if ("false".equals(properties.getProperty("fastjson.asmEnable"))) {
ParserConfig.global.setAsmEnable(false);
SerializeConfig.globalInstance.setAsmEnable(false);
}
}
}
/**
* config default type key
* @since 1.2.14
*/
public static void setDefaultTypeKey(String typeKey) {
DEFAULT_TYPE_KEY = typeKey;
ParserConfig.global.symbolTable.addSymbol(typeKey,
0,
typeKey.length(),
typeKey.hashCode(), true);
}
public static Object parse(String text) {
return parse(text, DEFAULT_PARSER_FEATURE);
}
/**
*
* @since 1.2.38
*/
public static Object parse(String text, ParserConfig config) {
return parse(text, config, DEFAULT_PARSER_FEATURE);
}
/**
*
* @since 1.2.68
*/
public static Object parse(String text, ParserConfig config, Feature... features) {
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
return parse(text, config, featureValues);
}
/**
*
* @since 1.2.38
*/
public static Object parse(String text, ParserConfig config, int features) {
if (text == null) {
return null;
}
DefaultJSONParser parser = new DefaultJSONParser(text, config, features);
Object value = parser.parse();
parser.handleResovleTask(value);
parser.close();
return value;
}
public static Object parse(String text, int features) {
return parse(text, ParserConfig.getGlobalInstance(), features);
}
public static Object parse(byte[] input, Feature... features) {
char[] chars = allocateChars(input.length);
int len = IOUtils.decodeUTF8(input, 0, input.length, chars);
if (len < 0) {
return null;
}
return parse(new String(chars, 0, len), features);
}
public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, Feature... features) {
if (input == null || input.length == 0) {
return null;
}
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
return parse(input, off, len, charsetDecoder, featureValues);
}
public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) {
charsetDecoder.reset();
int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
char[] chars = allocateChars(scaleLength);
ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
CharBuffer charBuf = CharBuffer.wrap(chars);
IOUtils.decode(charsetDecoder, byteBuf, charBuf);
int position = charBuf.position();
DefaultJSONParser parser = new DefaultJSONParser(chars, position, ParserConfig.getGlobalInstance(), features);
Object value = parser.parse();
parser.handleResovleTask(value);
parser.close();
return value;
}
public static Object parse(String text, Feature... features) {
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
return parse(text, featureValues);
}
public static JSONObject parseObject(String text, Feature... features) {
return (JSONObject) parse(text, features);
}
public static JSONObject parseObject(String text) {
Object obj = parse(text);
if (obj instanceof JSONObject) {
return (JSONObject) obj;
}
try {
return (JSONObject) JSON.toJSON(obj);
} catch (RuntimeException e) {
throw new JSONException("can not cast to JSONObject.", e);
}
}
/**
* <pre>
* String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"}]";
* List<Model> models = JSON.parseObject(jsonStr, new TypeReference<List<Model>>() {});
* </pre>
* @param text json string
* @param type type refernce
* @param features parser features
* @return an object of type T from the string
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(String text, TypeReference<T> type, Feature... features) {
return (T) parseObject(text, type.type, ParserConfig.global, DEFAULT_PARSER_FEATURE, features);
}
/**
*
* This method deserializes the specified Json into an object of the specified class. It is not
* suitable to use if the specified class is a generic type since it will not have the generic
* type information because of the Type Erasure feature of Java. Therefore, this method should not
* be used if the desired type is a generic type. Note that this method works fine if the any of
* the fields of the specified object are generics, just the object itself should not be a
* generic type. For the cases when the object is of generic type, invoke
* {@link #parseObject(String, Type, Feature[])}. If you have the Json in a {@link InputStream} instead of
* a String, use {@link #parseObject(InputStream, Type, Feature[])} instead.
*
* @param json the string from which the object is to be deserialized
* @param clazz the class of T
* @param features parser features
* @return an object of type T from the string
* classOfT
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(String json, Class<T> clazz, Feature... features) {
return (T) parseObject(json, (Type) clazz, ParserConfig.global, null, DEFAULT_PARSER_FEATURE, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String text, Class<T> clazz, ParseProcess processor, Feature... features) {
return (T) parseObject(text, (Type) clazz, ParserConfig.global, processor, DEFAULT_PARSER_FEATURE,
features);
}
/**
* This method deserializes the specified Json into an object of the specified type. This method
* is useful if the specified object is a generic type. For non-generic objects, use
* {@link #parseObject(String, Class, Feature[])} instead. If you have the Json in a {@link InputStream} instead of
* a String, use {@link #parseObject(InputStream, Type, Feature[])} instead.
*
* @param <T> the type of the desired object
* @param json the string from which the object is to be deserialized
* @param type The specific genericized type of src. You can obtain this type by using the
* {@link com.alibaba.fastjson.TypeReference} class. For example, to get the type for
* {@code Collection<Foo>}, you should use:
* <pre>
* Type type = new TypeReference<Collection<Foo>>(){}.getType();
* </pre>
* @return an object of type T from the string
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(String json, Type type, Feature... features) {
return (T) parseObject(json, type, ParserConfig.global, DEFAULT_PARSER_FEATURE, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParseProcess processor, Feature... features) {
return (T) parseObject(input, clazz, ParserConfig.global, processor, DEFAULT_PARSER_FEATURE, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, int featureValues, Feature... features) {
if (input == null) {
return null;
}
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
DefaultJSONParser parser = new DefaultJSONParser(input, ParserConfig.getGlobalInstance(), featureValues);
T value = (T) parser.parseObject(clazz);
parser.handleResovleTask(value);
parser.close();
return (T) value;
}
/**
* @since 1.2.11
*/
public static <T> T parseObject(String input, Type clazz, ParserConfig config, Feature... features) {
return parseObject(input, clazz, config, null, DEFAULT_PARSER_FEATURE, features);
}
public static <T> T parseObject(String input, Type clazz, ParserConfig config, int featureValues,
Feature... features) {
return parseObject(input, clazz, config, null, featureValues, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor,
int featureValues, Feature... features) {
if (input == null || input.length() == 0) {
return null;
}
if (features != null) {
for (Feature feature : features) {
featureValues |= feature.mask;
}
}
DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);
if (processor != null) {
if (processor instanceof ExtraTypeProvider) {
parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
}
if (processor instanceof ExtraProcessor) {
parser.getExtraProcessors().add((ExtraProcessor) processor);
}
if (processor instanceof FieldTypeResolver) {
parser.setFieldTypeResolver((FieldTypeResolver) processor);
}
}
T value = (T) parser.parseObject(clazz, null);
parser.handleResovleTask(value);
parser.close();
return (T) value;
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, Type clazz, Feature... features) {
return (T) parseObject(bytes, 0, bytes.length, IOUtils.UTF8, clazz, features);
}
/**
* @since 1.2.11
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature... features) {
return (T) parseObject(bytes, offset, len, charset, clazz, ParserConfig.global, null, DEFAULT_PARSER_FEATURE, features);
}
/**
* @since 1.2.55
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes,
Charset charset,
Type clazz,
ParserConfig config,
ParseProcess processor,
int featureValues,
Feature... features) {
return (T) parseObject(bytes, 0, bytes.length, charset, clazz, config, processor, featureValues, features);
}
/**
* @since 1.2.55
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] bytes, int offset, int len,
Charset charset,
Type clazz,
ParserConfig config,
ParseProcess processor,
int featureValues,
Feature... features) {
if (charset == null) {
charset = IOUtils.UTF8;
}
String strVal = null;
if (charset == IOUtils.UTF8) {
char[] chars = allocateChars(bytes.length);
int chars_len = IOUtils.decodeUTF8(bytes, offset, len, chars);
if (chars_len < 0) {
InputStreamReader gzipReader = null;
try {
gzipReader = new InputStreamReader(
new GZIPInputStream(
new ByteArrayInputStream(bytes, offset, len)), "UTF-8");
strVal = IOUtils.readAll(gzipReader);
} catch (Exception ex) {
return null;
} finally {
IOUtils.close(gzipReader);
}
}
if (strVal == null && chars_len < 0) {
return null;
}
if (strVal == null) {
strVal = new String(chars, 0, chars_len);
}
} else {
if (len < 0) {
return null;
}
strVal = new String(bytes, offset, len, charset);
}
return (T) parseObject(strVal, clazz, config, processor, featureValues, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(byte[] input, //
int off, //
int len, //
CharsetDecoder charsetDecoder, //
Type clazz, //
Feature... features) {
charsetDecoder.reset();
int scaleLength = (int) (len * (double) charsetDecoder.maxCharsPerByte());
char[] chars = allocateChars(scaleLength);
ByteBuffer byteBuf = ByteBuffer.wrap(input, off, len);
CharBuffer charByte = CharBuffer.wrap(chars);
IOUtils.decode(charsetDecoder, byteBuf, charByte);
int position = charByte.position();
return (T) parseObject(chars, position, clazz, features);
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(char[] input, int length, Type clazz, Feature... features) {
if (input == null || input.length == 0) {
return null;
}
int featureValues = DEFAULT_PARSER_FEATURE;
for (Feature feature : features) {
featureValues = Feature.config(featureValues, feature, true);
}
DefaultJSONParser parser = new DefaultJSONParser(input, length, ParserConfig.getGlobalInstance(), featureValues);
T value = (T) parser.parseObject(clazz);
parser.handleResovleTask(value);
parser.close();
return (T) value;
}
/**
* @since 1.2.11
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
Type type, //
Feature... features) throws IOException {
return (T) parseObject(is, IOUtils.UTF8, type, features);
}
/**
* @since 1.2.11
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
Charset charset, //
Type type, //
Feature... features) throws IOException {
return (T) parseObject(is, charset, type, ParserConfig.global, features);
}
/**
* @since 1.2.55
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
Charset charset, //
Type type, //
ParserConfig config, //
Feature... features) throws IOException {
return (T) parseObject(is, charset, type, config, null, DEFAULT_PARSER_FEATURE, features);
}
/**
* @since 1.2.55
*/
@SuppressWarnings("unchecked")
public static <T> T parseObject(InputStream is, //
Charset charset, //
Type type, //
ParserConfig config, //
ParseProcess processor, //
int featureValues, //
Feature... features) throws IOException {
if (charset == null) {
charset = IOUtils.UTF8;
}
byte[] bytes = allocateBytes(1024 * 64);
int offset = 0;
for (;;) {
int readCount = is.read(bytes, offset, bytes.length - offset);
if (readCount == -1) {
break;
}
offset += readCount;
if (offset == bytes.length) {
byte[] newBytes = new byte[bytes.length * 3 / 2];
System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
bytes = newBytes;
}
}
return (T) parseObject(bytes, 0, offset, charset, type, config, processor, featureValues, features);
}
public static <T> T parseObject(String text, Class<T> clazz) {
return parseObject(text, clazz, new Feature[0]);
}
public static JSONArray parseArray(String text) {
return parseArray(text, ParserConfig.global);
}
public static JSONArray parseArray(String text, ParserConfig parserConfig) {
if (text == null) {
return null;
}
DefaultJSONParser parser = new DefaultJSONParser(text, parserConfig);
JSONArray array;
JSONLexer lexer = parser.lexer;
if (lexer.token() == JSONToken.NULL) {
lexer.nextToken();
array = null;
} else if (lexer.token() == JSONToken.EOF && lexer.isBlankInput()) {
array = null;
} else {
array = new JSONArray();
parser.parseArray(array);
parser.handleResovleTask(array);
}
parser.close();
return array;
}
public static <T> List<T> parseArray(String text, Class<T> clazz) {
return parseArray(text, clazz, ParserConfig.global);
}
public static <T> List<T> parseArray(String text, Class<T> clazz, ParserConfig config) {
if (text == null) {
return null;
}
List<T> list;
DefaultJSONParser parser = new DefaultJSONParser(text, config);
JSONLexer lexer = parser.lexer;
int token = lexer.token();
if (token == JSONToken.NULL) {
lexer.nextToken();
list = null;
} else if (token == JSONToken.EOF && lexer.isBlankInput()) {
list = null;
} else {
list = new ArrayList<T>();
parser.parseArray(clazz, list);
parser.handleResovleTask(list);
}
parser.close();
return list;
}
public static List<Object> parseArray(String text, Type[] types) {
return parseArray(text, types, ParserConfig.global);
}
public static List<Object> parseArray(String text, Type[] types, ParserConfig config) {
if (text == null) {
return null;
}
List<Object> list;
DefaultJSONParser parser = new DefaultJSONParser(text, config);
Object[] objectArray = parser.parseArray(types);
if (objectArray == null) {
list = null;
} else {
list = Arrays.asList(objectArray);
}
parser.handleResovleTask(list);
parser.close();
return list;
}
/**
* This method serializes the specified object into its equivalent Json representation. Note that this method works fine if the any of the object fields are of generic type,
* just the object itself should not be of a generic type. If you want to write out the object to a
* {@link Writer}, use {@link #writeJSONString(Writer, Object, SerializerFeature[])} instead.
*
* @param object the object for which json representation is to be created setting for fastjson
* @return Json representation of {@code object}.
*/
public static String toJSONString(Object object) {
return toJSONString(object, emptyFilters);
}
public static String toJSONString(Object object, SerializerFeature... features) {
return toJSONString(object, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.11
*/
public static String toJSONString(Object object, int defaultFeatures, SerializerFeature... features) {
SerializeWriter out = new SerializeWriter((Writer) null, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out);
serializer.write(object);
String outString = out.toString();
int len = outString.length();
if (len > 0
&& outString.charAt(len -1) == '.'
&& object instanceof Number
&& !out.isEnabled(SerializerFeature.WriteClassName)) {
return outString.substring(0, len - 1);
}
return outString;
} finally {
out.close();
}
}
/**
* @since 1.1.14
*/
public static String toJSONStringWithDateFormat(Object object, String dateFormat,
SerializerFeature... features) {
return toJSONString(object, SerializeConfig.globalInstance, null, dateFormat, DEFAULT_GENERATE_FEATURE, features);
}
public static String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) {
return toJSONString(object, SerializeConfig.globalInstance, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features);
}
public static String toJSONString(Object object, SerializeFilter[] filters, SerializerFeature... features) {
return toJSONString(object, SerializeConfig.globalInstance, filters, null, DEFAULT_GENERATE_FEATURE, features);
}
public static byte[] toJSONBytes(Object object, SerializerFeature... features) {
return toJSONBytes(object, DEFAULT_GENERATE_FEATURE, features);
}
public static byte[] toJSONBytes(Object object, SerializeFilter filter, SerializerFeature... features) {
return toJSONBytes(object, SerializeConfig.globalInstance, new SerializeFilter[] {filter}, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.11
*/
public static byte[] toJSONBytes(Object object, int defaultFeatures, SerializerFeature... features) {
return toJSONBytes(object, SerializeConfig.globalInstance, defaultFeatures, features);
}
public static String toJSONString(Object object, SerializeConfig config, SerializerFeature... features) {
return toJSONString(object, config, (SerializeFilter) null, features);
}
public static String toJSONString(Object object, //
SerializeConfig config, //
SerializeFilter filter, //
SerializerFeature... features) {
return toJSONString(object, config, new SerializeFilter[] {filter}, null, DEFAULT_GENERATE_FEATURE, features);
}
public static String toJSONString(Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
SerializerFeature... features) {
return toJSONString(object, config, filters, null, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.9
* @return
*/
public static String toJSONString(Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
String dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out, config);
if (dateFormat != null && dateFormat.length() != 0) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
return out.toString();
} finally {
out.close();
}
}
/**
* @deprecated
*/
public static String toJSONStringZ(Object object, SerializeConfig mapping, SerializerFeature... features) {
return toJSONString(object, mapping, emptyFilters, null, 0, features);
}
/**
* @since 1.2.42
*/
public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializerFeature... features) {
return toJSONBytes(object, config, emptyFilters, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.11
*/
public static byte[] toJSONBytes(Object object, SerializeConfig config, int defaultFeatures, SerializerFeature... features) {
return toJSONBytes(object, config, emptyFilters, defaultFeatures, features);
}
/**
* @since 1.2.42
*/
public static byte[] toJSONBytes(Object object, SerializeFilter[] filters, SerializerFeature... features) {
return toJSONBytes(object, SerializeConfig.globalInstance, filters, DEFAULT_GENERATE_FEATURE, features);
}
public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter filter, SerializerFeature... features) {
return toJSONBytes(object, config, new SerializeFilter[] {filter}, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.42
*/
public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter[] filters, int defaultFeatures, SerializerFeature... features) {
return toJSONBytes(object, config, filters, null, defaultFeatures, features);
}
/**
* @since 1.2.55
*/
public static byte[] toJSONBytes(Object object, SerializeConfig config, SerializeFilter[] filters, String dateFormat, int defaultFeatures, SerializerFeature... features) {
return toJSONBytes(IOUtils.UTF8, object, config, filters, dateFormat, defaultFeatures, features);
}
/**
* @since 1.2.55
*/
public static byte[] toJSONBytes(Charset charset, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
String dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out, config);
if (dateFormat != null && dateFormat.length() != 0) {
serializer.setDateFormat(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
return out.toBytes(charset);
} finally {
out.close();
}
}
/**
* Use the date format in FastJsonConfig to serialize JSON
*
* @param dateFormat the date format in FastJsonConfigs
* @since 1.2.55
*/
public static byte[] toJSONBytesWithFastJsonConfig(Charset charset, //
Object object, //
SerializeConfig config, //
SerializeFilter[] filters, //
String dateFormat, //
int defaultFeatures, //
SerializerFeature... features) {
SerializeWriter out = new SerializeWriter(null, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out, config);
if (dateFormat != null && dateFormat.length() != 0) {
serializer.setFastJsonConfigDateFormatPattern(dateFormat);
serializer.config(SerializerFeature.WriteDateUseDateFormat, true);
}
if (filters != null) {
for (SerializeFilter filter : filters) {
serializer.addFilter(filter);
}
}
serializer.write(object);
return out.toBytes(charset);
} finally {
out.close();
}
}
public static String toJSONString(Object object, boolean prettyFormat) {
if (!prettyFormat) {
return toJSONString(object);
}
return toJSONString(object, SerializerFeature.PrettyFormat);
}
/**
* @deprecated use writeJSONString
*/
public static void writeJSONStringTo(Object object, Writer writer, SerializerFeature... features) {
writeJSONString(writer, object, features);
}
/**
* This method serializes the specified object into its equivalent json representation.
*
* @param writer Writer to which the json representation needs to be written
* @param object the object for which json representation is to be created setting for fastjson
* @param features serializer features
* @since 1.2.11
*/
public static void writeJSONString(Writer writer, Object object, SerializerFeature... features) {
writeJSONString(writer, object, JSON.DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.11
*/
public static void writeJSONString(Writer writer, Object object, int defaultFeatures, SerializerFeature... features) {
SerializeWriter out = new SerializeWriter(writer, defaultFeatures, features);
try {
JSONSerializer serializer = new JSONSerializer(out);
serializer.write(object);
} finally {
out.close();
}
}
/**
* write object as json to OutputStream
* @param os output stream
* @param object
* @param features serializer features
* @since 1.2.11
* @throws IOException
*/
public static final int writeJSONString(OutputStream os, //
Object object, //
SerializerFeature... features) throws IOException {
return writeJSONString(os, object, DEFAULT_GENERATE_FEATURE, features);
}
/**
* @since 1.2.11
*/
public static final int writeJSONString(OutputStream os, //
Object object, //
int defaultFeatures, //
SerializerFeature... features) throws IOException {
return writeJSONString(os, //
IOUtils.UTF8, //
object, //
SerializeConfig.globalInstance, //
null, //
null, //
defaultFeatures, //
features);
}
public static final int writeJSONString(OutputStream os, //
Charset charset, //
Object object, //
SerializerFeature... features) throws IOException {
return writeJSONString(os, //
charset, //
object, //
SerializeConfig.globalInstance, //
null, //
null, //
DEFAULT_GENERATE_FEATURE, //
features);
}