Skip to content

Commit ca70501

Browse files
Merge pull request #108 from lewisheadden/IntOrStringSupport
Add IntOrString model and GSON adapter
2 parents e085bc9 + ef5f427 commit ca70501

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package io.kubernetes.client.custom;
2+
3+
import com.google.gson.TypeAdapter;
4+
import com.google.gson.annotations.JsonAdapter;
5+
import com.google.gson.stream.JsonReader;
6+
import com.google.gson.stream.JsonToken;
7+
import com.google.gson.stream.JsonWriter;
8+
9+
import java.io.IOException;
10+
11+
@JsonAdapter(IntOrString.IntOrStringAdapter.class)
12+
public class IntOrString {
13+
private final boolean isInt;
14+
private final String strValue;
15+
private final Integer intValue;
16+
17+
public IntOrString(final String value) {
18+
this.isInt = false;
19+
this.strValue = value;
20+
this.intValue = null;
21+
}
22+
23+
public IntOrString(final int value) {
24+
this.isInt = true;
25+
this.intValue = value;
26+
this.strValue = null;
27+
}
28+
29+
public boolean isInteger() {
30+
return isInt;
31+
}
32+
33+
public String getStrValue() {
34+
if (isInt) {
35+
throw new IllegalStateException("Not a string");
36+
}
37+
return strValue;
38+
}
39+
40+
public Integer getIntValue() {
41+
if (!isInt) {
42+
throw new IllegalStateException("Not an integer");
43+
}
44+
return intValue;
45+
}
46+
47+
public static class IntOrStringAdapter extends TypeAdapter<IntOrString> {
48+
@Override
49+
public void write(JsonWriter jsonWriter, IntOrString intOrString) throws IOException {
50+
if (intOrString.isInteger()) {
51+
jsonWriter.value(intOrString.getIntValue());
52+
} else {
53+
jsonWriter.value(intOrString.getStrValue());
54+
}
55+
}
56+
57+
@Override
58+
public IntOrString read(JsonReader jsonReader) throws IOException {
59+
final JsonToken nextToken = jsonReader.peek();
60+
if (nextToken == JsonToken.NUMBER) {
61+
return new IntOrString(jsonReader.nextInt());
62+
} else if (nextToken == JsonToken.STRING) {
63+
return new IntOrString(jsonReader.nextString());
64+
} else {
65+
throw new IllegalStateException("Could not deserialize to IntOrString. Was " + nextToken);
66+
}
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)