-
Notifications
You must be signed in to change notification settings - Fork 0
/
moshi.go
885 lines (779 loc) · 29.6 KB
/
moshi.go
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
package models
import (
"fmt"
"github.com/specgen-io/specgen/v2/goven/generator"
"github.com/specgen-io/specgen/v2/goven/java/packages"
"github.com/specgen-io/specgen/v2/goven/java/types"
"github.com/specgen-io/specgen/v2/goven/java/writer"
"github.com/specgen-io/specgen/v2/goven/spec"
"strings"
)
var Moshi = "moshi"
var moshiCustomAdapters = `CustomMoshiAdapters`
type MoshiGenerator struct {
generatedSetupMoshiMethods []string
Types *types.Types
Packages *Packages
}
func NewMoshiGenerator(types *types.Types, packages *Packages) *MoshiGenerator {
return &MoshiGenerator{[]string{}, types, packages}
}
func (g *MoshiGenerator) Models(version *spec.Version) []generator.CodeFile {
return g.models(version.ResolvedModels, g.Packages.Models(version))
}
func (g *MoshiGenerator) ErrorModels(httperrors *spec.HttpErrors) []generator.CodeFile {
return g.models(httperrors.ResolvedModels, g.Packages.ErrorsModels)
}
func (g *MoshiGenerator) models(models []*spec.NamedModel, modelsPackage packages.Package) []generator.CodeFile {
files := []generator.CodeFile{}
for _, model := range models {
if model.IsObject() {
files = append(files, *g.modelObject(model, modelsPackage))
} else if model.IsOneOf() {
files = append(files, *g.modelOneOf(model, modelsPackage))
} else if model.IsEnum() {
files = append(files, *g.modelEnum(model, modelsPackage))
}
}
g.generatedSetupMoshiMethods = append(g.generatedSetupMoshiMethods, fmt.Sprintf(`%s.ModelsMoshiAdapters.setup`, modelsPackage.PackageName))
for range g.generatedSetupMoshiMethods {
files = append(files, *g.setupOneOfAdapters(models, modelsPackage))
}
return files
}
func (g *MoshiGenerator) modelObject(model *spec.NamedModel, thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, model.Name.PascalCase())
w.Imports.Add(g.modelsDefinitionsImports()...)
w.Imports.Add(g.Types.Imports()...)
w.EmptyLine()
w.Line(`public class [[.ClassName]] {`)
for _, field := range model.Object.Fields {
w.EmptyLine()
w.Line(` @Json(name = "%s")`, field.Name.Source)
w.Line(` private %s %s;`, g.Types.Java(&field.Type.Definition), field.Name.CamelCase())
}
w.EmptyLine()
ctorParams := []string{}
for _, field := range model.Object.Fields {
ctorParams = append(ctorParams, fmt.Sprintf(`%s %s`, g.Types.Java(&field.Type.Definition), field.Name.CamelCase()))
}
w.Line(` public %s(%s) {`, model.Name.PascalCase(), strings.Join(ctorParams, ", "))
for _, field := range model.Object.Fields {
w.Line(` this.%s = %s;`, field.Name.CamelCase(), field.Name.CamelCase())
}
w.Line(` }`)
for _, field := range model.Object.Fields {
w.EmptyLine()
w.Line(` public %s %s() {`, g.Types.Java(&field.Type.Definition), getterName(&field))
w.Line(` return %s;`, field.Name.CamelCase())
w.Line(` }`)
w.EmptyLine()
w.Line(` public void %s(%s %s) {`, setterName(&field), g.Types.Java(&field.Type.Definition), field.Name.CamelCase())
w.Line(` this.%s = %s;`, field.Name.CamelCase(), field.Name.CamelCase())
w.Line(` }`)
}
w.EmptyLine()
addObjectModelMethods(w.Indented(), model)
w.Line(`}`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) modelEnum(model *spec.NamedModel, thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, model.Name.PascalCase())
w.Imports.Add(g.modelsDefinitionsImports()...)
w.Imports.Add(g.Types.Imports()...)
w.EmptyLine()
w.Line(`public enum [[.ClassName]] {`)
for _, enumItem := range model.Enum.Items {
w.Line(` @Json(name = "%s") %s,`, enumItem.Value, enumItem.Name.UpperCase())
}
w.Line(`}`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) modelOneOf(model *spec.NamedModel, thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, model.Name.PascalCase())
w.Imports.Add(g.modelsDefinitionsImports()...)
w.Imports.Add(g.Types.Imports()...)
w.EmptyLine()
w.Line(`public interface [[.ClassName]] {`)
for index, item := range model.OneOf.Items {
if index > 0 {
w.EmptyLine()
}
g.modelOneOfImplementation(w.Indented(), &item, model)
}
w.Line(`}`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) modelOneOfImplementation(w *writer.Writer, item *spec.NamedDefinition, model *spec.NamedModel) {
w.Line(`class %s implements %s {`, oneOfItemClassName(item), model.Name.PascalCase())
w.Line(` public %s data;`, g.Types.Java(&item.Type.Definition))
w.EmptyLine()
w.Line(` public %s() {`, oneOfItemClassName(item))
w.Line(` }`)
w.EmptyLine()
w.Line(` public %s(%s data) {`, oneOfItemClassName(item), g.Types.Java(&item.Type.Definition))
if !item.Type.Definition.IsNullable() && g.Types.IsReference(&item.Type.Definition) {
w.Line(` if (data == null) { throw new IllegalArgumentException("null value is not allowed"); }`)
}
w.Line(` this.data = data;`)
w.Line(` }`)
w.EmptyLine()
w.Line(` public %s getData() {`, g.Types.Java(&item.Type.Definition))
w.Line(` return data;`)
w.Line(` }`)
w.EmptyLine()
w.Line(` public void setData(%s data) {`, g.Types.Java(&item.Type.Definition))
if !item.Type.Definition.IsNullable() && g.Types.IsReference(&item.Type.Definition) {
w.Line(` if (data == null) { throw new IllegalArgumentException("null value is not allowed"); }`)
}
w.Line(` this.data = data;`)
w.Line(` }`)
w.EmptyLine()
w.Indent()
addOneOfModelMethods(w, item)
w.Unindent()
w.Line(`}`)
}
func (g *MoshiGenerator) JsonRead(varJson string, typ *spec.TypeDef) string {
adapterParam := fmt.Sprintf(`%s.class`, g.Types.Java(typ))
if typ.Node == spec.MapType {
typeJava := g.Types.Java(typ.Child)
adapterParam = fmt.Sprintf(`Types.newParameterizedType(Map.class, String.class, %s.class)`, typeJava)
}
if typ.Node == spec.ArrayType {
typeJava := g.Types.Java(typ.Child)
adapterParam = fmt.Sprintf(`Types.newParameterizedType(List.class, %s.class)`, typeJava)
}
return fmt.Sprintf(`read(%s, %s)`, varJson, adapterParam)
}
func (g *MoshiGenerator) JsonWrite(varData string, typ *spec.TypeDef) string {
adapterParam := fmt.Sprintf(`%s.class`, g.Types.Java(typ))
if typ.Node == spec.MapType {
typeJava := g.Types.Java(typ.Child)
adapterParam = fmt.Sprintf(`Types.newParameterizedType(Map.class, String.class, %s.class)`, typeJava)
}
if typ.Node == spec.ArrayType {
typeJava := g.Types.Java(typ.Child)
adapterParam = fmt.Sprintf(`Types.newParameterizedType(List.class, %s.class)`, typeJava)
}
return fmt.Sprintf(`write(%s, %s)`, adapterParam, varData)
}
func (g *MoshiGenerator) modelsDefinitionsImports() []string {
return []string{
`com.squareup.moshi.Json`,
`com.squareup.moshi.Moshi`,
`com.squareup.moshi.Types`,
}
}
func (g *MoshiGenerator) ModelsUsageImports() []string {
return []string{
`com.squareup.moshi.Moshi`,
`com.squareup.moshi.Types`,
`java.lang.reflect.ParameterizedType`,
}
}
func (g *MoshiGenerator) ValidationErrorsHelpers() *generator.CodeFile {
w := writer.New(g.Packages.Errors, `ValidationErrorsHelpers`)
w.Template(
map[string]string{
`JsonPackage`: g.Packages.Json.PackageName,
`ErrorsModelsPackage`: g.Packages.ErrorsModels.PackageName,
}, `
import [[.JsonPackage]].*;
import [[.ErrorsModelsPackage]].*;
import java.util.List;
import java.util.regex.Pattern;
public class [[.ClassName]] {
private static final Pattern pathPattern = Pattern.compile("\\$\\.([^ ]+)");
public static List<ValidationError> extractValidationErrors(JsonParseException exception) {
var matcher = pathPattern.matcher(exception.getMessage());
if (matcher.find()) {
var jsonPath = matcher.group(1);
return List.of(new ValidationError(jsonPath, "parsing_failed", exception.getMessage()));
}
return null;
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) JsonHelpers() []generator.CodeFile {
files := []generator.CodeFile{}
files = append(files, *g.json())
files = append(files, *g.jsonParseException())
files = append(files, *g.textReader())
files = append(files, g.setupLibrary()...)
return files
}
func (g *MoshiGenerator) json() *generator.CodeFile {
w := writer.New(g.Packages.Json, `Json`)
w.Imports.StaticStar(g.Packages.Json.Subpackage(`TextReader`))
w.Lines(`
import com.squareup.moshi.Moshi;
import java.io.Reader;
import java.lang.reflect.ParameterizedType;
public class [[.ClassName]] {
private final Moshi moshi;
public [[.ClassName]](Moshi moshi) {
this.moshi = moshi;
}
public <T> String write(Class<T> type, T data) {
return moshi.adapter(type).toJson(data);
}
public <T> String write(ParameterizedType type, T data) {
return moshi.adapter(type).toJson(data);
}
public <T> T read(String jsonStr, Class<T> type) {
try {
return moshi.adapter(type).fromJson(jsonStr);
} catch (Exception exception) {
throw new JsonParseException(exception);
}
}
public <T> T read(String jsonStr, ParameterizedType type) {
try {
return moshi.<T>adapter(type).fromJson(jsonStr);
} catch (Exception exception) {
throw new JsonParseException(exception);
}
}
public <T> T read(Reader reader, Class<T> type) {
try {
return moshi.adapter(type).fromJson(readText(reader));
} catch (Exception exception) {
throw new JsonParseException(exception);
}
}
public <T> T read(Reader reader, ParameterizedType type) {
try {
return moshi.<T>adapter(type).fromJson(readText(reader));
} catch (Exception exception) {
throw new JsonParseException(exception);
}
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) textReader() *generator.CodeFile {
w := writer.New(g.Packages.Json, `TextReader`)
w.Lines(`
import java.io.*;
public class [[.ClassName]] {
public static String readText(Reader reader) throws IOException {
char[] buffer = new char[4096];
StringBuilder builder = new StringBuilder();
int numChars;
while ((numChars = reader.read(buffer)) >= 0) {
builder.append(buffer, 0, numChars);
}
return builder.toString();
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) jsonParseException() *generator.CodeFile {
w := writer.New(g.Packages.Json, `JsonParseException`)
w.Lines(`
public class [[.ClassName]] extends RuntimeException {
public [[.ClassName]](Throwable exception) {
super("Failed to parse body: " + exception.getMessage(), exception);
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) setupLibrary() []generator.CodeFile {
files := []generator.CodeFile{}
files = append(files, *g.setupAdapters())
files = append(files, *bigDecimalAdapter(g.Packages.JsonAdapters))
files = append(files, *localDateAdapter(g.Packages.JsonAdapters))
files = append(files, *localDateTimeAdapter(g.Packages.JsonAdapters))
files = append(files, *uuidAdapter(g.Packages.JsonAdapters))
files = append(files, *unionAdapterFactory(g.Packages.JsonAdapters))
files = append(files, *unwrapFieldAdapterFactory(g.Packages.JsonAdapters))
return files
}
func (g *MoshiGenerator) setupAdapters() *generator.CodeFile {
w := writer.New(g.Packages.Json, moshiCustomAdapters)
w.Imports.Add(`com.squareup.moshi.Moshi`)
w.Imports.Star(g.Packages.JsonAdapters)
w.Lines(`
public class [[.ClassName]] {
public static Moshi.Builder setup(Moshi.Builder moshiBuilder) {
moshiBuilder
.add(new BigDecimalAdapter())
.add(new UuidAdapter())
.add(new LocalDateAdapter())
.add(new LocalDateTimeAdapter());
`)
for _, setupMoshiMethod := range g.generatedSetupMoshiMethods {
w.Line(` %s(moshiBuilder);`, setupMoshiMethod)
}
w.EmptyLine()
w.Lines(`
return moshiBuilder;
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) setupOneOfAdapters(models []*spec.NamedModel, modelsPackage packages.Package) *generator.CodeFile {
w := writer.New(modelsPackage, `ModelsMoshiAdapters`)
w.Imports.Add(`com.squareup.moshi.Moshi`)
w.Imports.Star(g.Packages.JsonAdapters)
w.EmptyLine()
w.Line(`public class [[.ClassName]] {`)
w.Line(` public static void setup(Moshi.Builder moshiBuilder) {`)
for _, model := range models {
if model.IsOneOf() {
w.IndentWith(2)
w.Line(`moshiBuilder`)
modelName := model.Name.PascalCase()
for _, item := range model.OneOf.Items {
w.Line(` .add(new UnwrapFieldAdapterFactory(%s.%s.class))`, modelName, oneOfItemClassName(&item))
}
addUnionAdapterFactory := fmt.Sprintf(` .add(UnionAdapterFactory.of(%s.class)`, modelName)
if model.OneOf.Discriminator != nil {
w.Line(`%s.withDiscriminator("%s")`, addUnionAdapterFactory, *model.OneOf.Discriminator)
} else {
w.Line(addUnionAdapterFactory)
}
for _, item := range model.OneOf.Items {
w.Line(` .withSubtype(%s.%s.class, "%s")`, modelName, oneOfItemClassName(&item), item.Name.Source)
}
w.Line(` );`)
w.UnindentWith(2)
}
}
w.Line(` }`)
w.Line(`}`)
return w.ToCodeFile()
}
func bigDecimalAdapter(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `BigDecimalAdapter`)
w.Lines(`
import com.squareup.moshi.*;
import okio.Okio;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
public class [[.ClassName]] {
@FromJson
public BigDecimal fromJson(JsonReader reader) throws IOException {
var token = reader.peek();
if (token != JsonReader.Token.NUMBER) {
throw new JsonDataException("BigDecimal should be represented as number in JSON, found: "+token.name());
}
var source = reader.nextSource();
return new BigDecimal(new String(source.readByteArray(), StandardCharsets.UTF_8));
}
@ToJson
public void toJson(JsonWriter writer, BigDecimal value) throws IOException {
var source = Okio.source(new ByteArrayInputStream(value.toString().getBytes()));
var buffer = Okio.buffer(source);
writer.value(buffer);
}
}
`)
return w.ToCodeFile()
}
func localDateAdapter(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `LocalDateAdapter`)
w.Lines(`
import com.squareup.moshi.*;
import java.time.LocalDate;
public class [[.ClassName]] {
@FromJson
private LocalDate fromJson(String string) {
return LocalDate.parse(string);
}
@ToJson
private String toJson(LocalDate value) {
return value.toString();
}
}
`)
return w.ToCodeFile()
}
func localDateTimeAdapter(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `LocalDateTimeAdapter`)
w.Lines(`
import com.squareup.moshi.*;
import java.time.LocalDateTime;
public class [[.ClassName]] {
@FromJson
private LocalDateTime fromJson(String string) {
return LocalDateTime.parse(string);
}
@ToJson
private String toJson(LocalDateTime value) {
return value.toString();
}
}
`)
return w.ToCodeFile()
}
func uuidAdapter(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `UuidAdapter`)
w.Lines(`
import com.squareup.moshi.*;
import java.util.UUID;
public class [[.ClassName]] {
@FromJson
private UUID fromJson(String string) {
return UUID.fromString(string);
}
@ToJson
private String toJson(UUID value) {
return value.toString();
}
}
`)
return w.ToCodeFile()
}
func unionAdapterFactory(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `UnionAdapterFactory`)
w.Lines(`
import com.squareup.moshi.*;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.*;
import javax.annotation.*;
public final class [[.ClassName]]<T> implements JsonAdapter.Factory {
final Class<T> baseType;
final String discriminator;
final List<String> tags;
final List<Type> subtypes;
@Nullable final JsonAdapter<Object> fallbackAdapter;
[[.ClassName]](
Class<T> baseType,
String discriminator,
List<String> tags,
List<Type> subtypes,
@Nullable JsonAdapter<Object> fallbackAdapter) {
this.baseType = baseType;
this.discriminator = discriminator;
this.tags = tags;
this.subtypes = subtypes;
this.fallbackAdapter = fallbackAdapter;
}
/**
* @param baseType The base type for which this factory will create adapters. Cannot be Object.
* JSON object.
*/
@CheckReturnValue
public static <T> [[.ClassName]]<T> of(Class<T> baseType) {
if (baseType == null) throw new NullPointerException("baseType == null");
return new UnionAdapterFactory<>(baseType, null, Collections.<String>emptyList(), Collections.<Type>emptyList(), null);
}
/** Returns a new factory that decodes instances of {@code subtype}. */
public [[.ClassName]]<T> withDiscriminator(String discriminator) {
if (discriminator == null) throw new NullPointerException("discriminator == null");
return new UnionAdapterFactory<>(baseType, discriminator, tags, subtypes, fallbackAdapter);
}
/** Returns a new factory that decodes instances of {@code subtype}. */
public [[.ClassName]]<T> withSubtype(Class<? extends T> subtype, String tag) {
if (subtype == null) throw new NullPointerException("subtype == null");
if (tag == null) throw new NullPointerException("tag == null");
if (tags.contains(tag)) {
throw new IllegalArgumentException("Tags must be unique.");
}
List<String> newTags = new ArrayList<>(tags);
newTags.add(tag);
List<Type> newSubtypes = new ArrayList<>(subtypes);
newSubtypes.add(subtype);
return new UnionAdapterFactory<>(baseType, discriminator, newTags, newSubtypes, fallbackAdapter);
}
/**
* Returns a new factory that with default to {@code fallbackJsonAdapter.fromJson(reader)} upon
* decoding of unrecognized tags.
*
* <p>The {@link JsonReader} instance will not be automatically consumed, so make sure to consume
* it within your implementation of {@link JsonAdapter#fromJson(JsonReader)}
*/
public [[.ClassName]]<T> withFallbackAdapter(@Nullable JsonAdapter<Object> fallbackJsonAdapter) {
return new UnionAdapterFactory<>(baseType, discriminator, tags, subtypes, fallbackJsonAdapter);
}
/**
* Returns a new factory that will default to {@code defaultValue} upon decoding of unrecognized
* tags. The default value should be immutable.
*/
public [[.ClassName]]<T> withDefaultValue(@Nullable T defaultValue) {
return withFallbackAdapter(buildFallbackAdapter(defaultValue));
}
private JsonAdapter<Object> buildFallbackAdapter(final T defaultValue) {
return new JsonAdapter<Object>() {
@Override
public @Nullable Object fromJson(JsonReader reader) throws IOException {
reader.skipValue();
return defaultValue;
}
@Override
public void toJson(JsonWriter writer, Object value) throws IOException {
throw new IllegalArgumentException("Expected one of " + subtypes + " but found " + value + ", a " + value.getClass() + ". Register this subtype.");
}
};
}
@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
if (Types.getRawType(type) != baseType || !annotations.isEmpty()) {
return null;
}
List<JsonAdapter<Object>> jsonAdapters = new ArrayList<>(subtypes.size());
for (int i = 0, size = subtypes.size(); i < size; i++) {
jsonAdapters.add(moshi.adapter(subtypes.get(i)));
}
if (discriminator != null) {
return new UnionDiscriminatorAdapter(discriminator, tags, subtypes, jsonAdapters, fallbackAdapter).nullSafe();
} else {
return new UnionWrapperAdapter(tags, subtypes, jsonAdapters, fallbackAdapter).nullSafe();
}
}
static final class UnionDiscriminatorAdapter extends JsonAdapter<Object> {
final String discriminator;
final List<String> tags;
final List<Type> subtypes;
final List<JsonAdapter<Object>> adapters;
@Nullable final JsonAdapter<Object> fallbackAdapter;
final JsonReader.Options discriminatorOptions;
final JsonReader.Options tagsOptions;
UnionDiscriminatorAdapter(
String discriminator,
List<String> tags,
List<Type> subtypes,
List<JsonAdapter<Object>> adapters,
@Nullable JsonAdapter<Object> fallbackAdapter) {
this.discriminator = discriminator;
this.tags = tags;
this.subtypes = subtypes;
this.adapters = adapters;
this.fallbackAdapter = fallbackAdapter;
this.discriminatorOptions = JsonReader.Options.of(discriminator);
this.tagsOptions = JsonReader.Options.of(tags.toArray(new String[0]));
}
@Override
public Object fromJson(JsonReader reader) throws IOException {
final int tagIndex = getTagIndex(reader);
JsonAdapter<Object> adapter = fallbackAdapter;
if (tagIndex != -1) {
adapter = adapters.get(tagIndex);
}
return adapter.fromJson(reader);
}
@Override
public void toJson(JsonWriter writer, Object value) throws IOException {
int tagIndex = getTagIndex(value);
if (tagIndex == -1) {
fallbackAdapter.toJson(writer, value);
} else {
final JsonAdapter<Object> adapter = adapters.get(tagIndex);
writer.beginObject();
writer.name(discriminator).value(tags.get(tagIndex));
int flattenToken = writer.beginFlatten();
adapter.toJson(writer, value);
writer.endFlatten(flattenToken);
writer.endObject();
}
}
private int getTagIndex(JsonReader reader) throws IOException {
JsonReader peeked = reader.peekJson();
peeked.setFailOnUnknown(false);
try {
peeked.beginObject();
while (peeked.hasNext()) {
if (peeked.selectName(discriminatorOptions) == -1) {
peeked.skipName();
peeked.skipValue();
continue;
}
int tagIndex = peeked.selectString(tagsOptions);
if (tagIndex == -1 && this.fallbackAdapter == null) {
throw new JsonDataException("Expected one of " + tags + " for key '" + discriminator + "' but found '" + peeked.nextString() + "'. Register a subtype for this tag.");
}
return tagIndex;
}
throw new JsonDataException("Missing discriminator field " + discriminator);
} finally {
peeked.close();
}
}
private int getTagIndex(Object value) {
Class<?> type = value.getClass();
int tagIndex = subtypes.indexOf(type);
if (tagIndex == -1 && fallbackAdapter == null) {
throw new IllegalArgumentException("Expected one of " + subtypes + " but found " + value + ", a " + value.getClass() + ". Register this subtype.");
} else {
return tagIndex;
}
}
@Override
public String toString() {
return "UnionDiscriminatorAdapter(" + discriminator + ")";
}
}
static final class UnionWrapperAdapter extends JsonAdapter<Object> {
final List<String> tags;
final List<Type> subtypes;
final List<JsonAdapter<Object>> adapters;
@Nullable final JsonAdapter<Object> fallbackAdapter;
final JsonReader.Options tagsOptions;
UnionWrapperAdapter(
List<String> tags,
List<Type> subtypes,
List<JsonAdapter<Object>> adapters,
@Nullable JsonAdapter<Object> fallbackAdapter) {
this.tags = tags;
this.subtypes = subtypes;
this.adapters = adapters;
this.fallbackAdapter = fallbackAdapter;
this.tagsOptions = JsonReader.Options.of(tags.toArray(new String[0]));
}
@Override
public Object fromJson(JsonReader reader) throws IOException {
int tagIndex = getTagIndex(reader);
if (tagIndex == -1) {
return this.fallbackAdapter.fromJson(reader);
} else {
reader.beginObject();
reader.skipName();
final Object value = adapters.get(tagIndex).fromJson(reader);
reader.endObject();
return value;
}
}
@Override
public void toJson(JsonWriter writer, Object value) throws IOException {
int tagIndex = getTagIndex(value);
if (tagIndex == -1) {
fallbackAdapter.toJson(writer, value);
} else {
final JsonAdapter<Object> adapter = adapters.get(tagIndex);
writer.beginObject();
writer.name(tags.get(tagIndex));
adapter.toJson(writer, value);
writer.endObject();
}
}
private int getTagIndex(JsonReader reader) throws IOException {
JsonReader peeked = reader.peekJson();
peeked.setFailOnUnknown(false);
try {
peeked.beginObject();
int tagIndex = peeked.selectName(tagsOptions);
if (tagIndex == -1 && this.fallbackAdapter == null) {
throw new JsonDataException("Expected one of keys:" + tags + "' but found '" + peeked.nextString() + "'. Register a subtype for this tag.");
}
return tagIndex;
} finally {
peeked.close();
}
}
private int getTagIndex(Object value) {
Class<?> type = value.getClass();
int tagIndex = subtypes.indexOf(type);
if (tagIndex == -1 && fallbackAdapter == null) {
throw new IllegalArgumentException("Expected one of " + subtypes + " but found " + value + ", a " + value.getClass() + ". Register this subtype.");
}
return tagIndex;
}
@Override
public String toString() {
return "UnionWrapperAdapter";
}
}
}
`)
return w.ToCodeFile()
}
func unwrapFieldAdapterFactory(thePackage packages.Package) *generator.CodeFile {
w := writer.New(thePackage, `UnwrapFieldAdapterFactory`)
w.Line(`
import com.squareup.moshi.*;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.Set;
public final class [[.ClassName]]<T> implements JsonAdapter.Factory {
final Class<T> type;
public [[.ClassName]](Class<T> type) {
this.type = type;
}
@Nullable
@Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
if (Types.getRawType(type) != this.type || !annotations.isEmpty()) {
return null;
}
final Field[] fields = this.type.getDeclaredFields();
if (fields.length != 1) {
throw new RuntimeException("Type "+type.getTypeName()+" has "+fields.length+" fields, unwrap adapter can be used only with single-field classes");
}
var field = fields[0];
var fieldName = field.getName();
var getterName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1).toLowerCase();
Method getter;
try {
getter = this.type.getDeclaredMethod(getterName);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Type "+type.getTypeName()+" field "+fieldName+" does not have getter method "+ field.getType().getName()+", it's required for unwrap adapter", e);
}
Constructor<T> constructor;
try {
constructor = this.type.getDeclaredConstructor(field.getType());
} catch (NoSuchMethodException e) {
throw new RuntimeException("Type "+type.getTypeName()+" does not have constructor with single parameter of type "+ field.getType().getName()+", it's required for unwrap adapter", e);
}
JsonAdapter<?> fieldAdapter = moshi.adapter(field.getType());
return new UnwrapFieldAdapter(constructor, getter, fieldAdapter);
}
public class UnwrapFieldAdapter<O, I> extends JsonAdapter<Object> {
private Constructor<O> constructor;
private Method getter;
private JsonAdapter<I> fieldAdapter;
public UnwrapFieldAdapter(Constructor<O> constructor, Method getter, JsonAdapter<I> fieldAdapter) {
this.constructor = constructor;
this.getter = getter;
this.fieldAdapter = fieldAdapter;
}
@Override
public Object fromJson(JsonReader reader) throws IOException {
I fieldValue = fieldAdapter.fromJson(reader);
try {
return constructor.newInstance(fieldValue);
} catch (Throwable e) {
throw new IOException("Failed to create object with constructor "+constructor.getName(), e);
}
}
@Override
public void toJson(JsonWriter writer, Object value) throws IOException {
if (value == null) {
fieldAdapter.toJson(writer, null);
} else {
I fieldValue;
try {
fieldValue = (I) getter.invoke(value);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IOException("Failed to call method "+ getter.getName(), e);
}
fieldAdapter.toJson(writer, fieldValue);
}
}
@Override
public String toString() {
return "UnwrapFieldAdapter(" + getter.getName() + ")";
}
}
}
`)
return w.ToCodeFile()
}
func (g *MoshiGenerator) JsonMapperInit() string {
return fmt.Sprintf(`%s.setup(new Moshi.Builder()).build()`, moshiCustomAdapters)
}
func (g *MoshiGenerator) JsonMapperType() string {
return `Moshi`
}