Skip to content

Commit 9ae7641

Browse files
authored
Merge pull request #357 from brendandburns/parse
Add an example of how to parse and generate JSON.
2 parents 70a7b2b + 3ed70ba commit 9ae7641

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
Copyright 2018 The Kubernetes Authors.
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
Unless required by applicable law or agreed to in writing, software
8+
distributed under the License is distributed on an "AS IS" BASIS,
9+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+
See the License for the specific language governing permissions and
11+
limitations under the License.
12+
*/
13+
package io.kubernetes.client.examples;
14+
15+
import io.kubernetes.client.ApiClient;
16+
import io.kubernetes.client.ApiException;
17+
import io.kubernetes.client.util.Config;
18+
import java.io.FileReader;
19+
import java.io.IOException;
20+
import java.io.StringReader;
21+
22+
/**
23+
* A simple example of how to parse a Kubernetes object.
24+
*
25+
* <p>Easiest way to run this: mvn exec:java
26+
* -Dexec.mainClass="io.kubernetes.client.examples.ParseExample"
27+
*
28+
* <p>From inside $REPO_DIR/examples
29+
*/
30+
public class ParseExample {
31+
public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException {
32+
if (args.length < 2) {
33+
System.err.println("Usage: ParseExample <file-name> <class-name e.g. V1Pod>");
34+
System.exit(1);
35+
}
36+
ApiClient client = Config.defaultClient();
37+
FileReader json = new FileReader(args[0]);
38+
Object obj =
39+
client
40+
.getJSON()
41+
.getGson()
42+
.fromJson(json, Class.forName("io.kubernetes.client.models." + args[1]));
43+
44+
String output = client.getJSON().getGson().toJson(obj);
45+
46+
// Test round tripping...
47+
Object obj2 =
48+
client
49+
.getJSON()
50+
.getGson()
51+
.fromJson(
52+
new StringReader(output), Class.forName("io.kubernetes.client.models." + args[1]));
53+
54+
String output2 = client.getJSON().getGson().toJson(obj2);
55+
56+
// Validate round trip
57+
if (!output.equals(output2)) {
58+
System.err.println("Error, expected:\n" + output + "\nto equal\n" + output2);
59+
System.exit(2);
60+
}
61+
62+
System.out.println(output);
63+
}
64+
}

0 commit comments

Comments
 (0)