0

我正在阅读来自http://aws.amazon.com/ec2/pricing/pricing-ebs-optimized-instances.json的价格信息,下面是获取它的代码示例

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();
    }

}

我得到以下输出

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}}]}]}]

想从 instanceTypes 字符串中读取名称、价格和大小。

注意:我使用http://jsongen.byingtondesign.com/来生成 java 对象

4

1 回答 1

0

您可以选择使用 GSON 将这些映射到 Java 域对象中。

这是我过去制作的教程,您可能会发现它很有用:

http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/

于 2012-10-23T11:21:02.583 回答