1 /*
2  * Copyright (C) 2014 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.squareup.moshi;
17
18 import java.io.IOException;
19 import java.lang.annotation.Annotation;
20 import java.lang.reflect.Array;
21 import java.lang.reflect.Type;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Set;
25 import javax.annotation.Nullable;
26
27 /**
28  * Converts arrays to JSON arrays containing their converted contents. This
29  * supports both primitive and object arrays.
30  */

31 final class ArrayJsonAdapter extends JsonAdapter<Object> {
32   public static final Factory FACTORY = new Factory() {
33     @Override public @Nullable JsonAdapter<?> create(
34         Type type, Set<? extends Annotation> annotations, Moshi moshi) {
35       Type elementType = Types.arrayComponentType(type);
36       if (elementType == nullreturn null;
37       if (!annotations.isEmpty()) return null;
38       Class<?> elementClass = Types.getRawType(elementType);
39       JsonAdapter<Object> elementAdapter = moshi.adapter(elementType);
40       return new ArrayJsonAdapter(elementClass, elementAdapter).nullSafe();
41     }
42   };
43
44   private final Class<?> elementClass;
45   private final JsonAdapter<Object> elementAdapter;
46
47   ArrayJsonAdapter(Class<?> elementClass, JsonAdapter<Object> elementAdapter) {
48     this.elementClass = elementClass;
49     this.elementAdapter = elementAdapter;
50   }
51
52   @Override public Object fromJson(JsonReader reader) throws IOException {
53     List<Object> list = new ArrayList<>();
54     reader.beginArray();
55     while (reader.hasNext()) {
56       list.add(elementAdapter.fromJson(reader));
57     }
58     reader.endArray();
59     Object array = Array.newInstance(elementClass, list.size());
60     for (int i = 0; i < list.size(); i++) {
61       Array.set(array, i, list.get(i));
62     }
63     return array;
64   }
65
66   @Override public void toJson(JsonWriter writer, Object value) throws IOException {
67     writer.beginArray();
68     for (int i = 0, size = Array.getLength(value); i < size; i++) {
69       elementAdapter.toJson(writer, Array.get(value, i));
70     }
71     writer.endArray();
72   }
73
74   @Override public String toString() {
75     return elementAdapter + ".array()";
76   }
77 }
78