I am reading the price information from the http://aws.amazon.com/ec2/pricing/pricing-ebs-optimized-instances.json following is the code example to get it
public class SampleJson
{
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception
{
String json = readUrl("http://aws.amazon.com/ec2/pricing/pricing-ebs-optimized-instances.json");
Type collectionType = new TypeToken<EBS>()
{
}.getType();
EBS ebs = (EBS) new Gson().fromJson(json, collectionType);
Config config = ebs.getConfig();
ArrayList<StringMap<Regions>> region = (ArrayList<StringMap<Regions>>) config.getRegions();
for (StringMap<Regions> regObj : region)
{
Set<Entry<String, Regions>> reg = regObj.entrySet();
for (Map.Entry<String, Regions> data : reg)
{
Object key = data.getKey();
Object value = data.getValue();
System.out.print(key + ": ");
System.out.println(value);
}
}
}
private static String readUrl(String urlString) throws Exception
{
BufferedReader reader = null;
try
{
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}
}
I get the following out put
region: us-east
instanceTypes: [{type=std, sizes=[{size=lg, valueColumns=[{name=ebsOptimized, prices= {USD=0.025}}]}, {size=xl, valueColumns=[{name=ebsOptimized, prices={USD=0.05}}]}]}, {type=hiMem, sizes=[{size=xxxxl, valueColumns=[{name=ebsOptimized, prices={USD=0.05}}]}]}]
Wanted to read the name, prices and size from the instanceTypes String.
Note : I used http://jsongen.byingtondesign.com/ to generate the java objects
You have a choice of mapping these into Java domain objects using GSON.
Here is a tutorial I made in the past that you may find useful:
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/