【问题标题】:Java JSON with GSON带有 GSON 的 Java JSON
【发布时间】:2013-11-26 19:33:55
【问题描述】:

问题来了,我正在使用 Wunderground 的天气 APi,但在使用 GSON 获取天气时遇到了问题。

import java.net.*;
import java.io.*;
import com.google.gson.*;

public class URLReader {

    public static URL link;

    public static void main(String[] args) {
        try{
            open();
            read();
        }catch(IOException e){}
    }

    public static void open(){
        try{
            link = new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json");
        }catch(MalformedURLException e){}
    }

    public static void read() throws IOException{
        Gson gson = new Gson();

        // Code to get variables like humidity, chance of rain, ect...
    }
} 

就我所知,有人可以帮我解决这个问题。我需要能够解析特定变量,而不仅仅是整个 JSON 文件。

我使用了缓冲阅读器,但它读取了整个 JSON 文件。

在此先感谢,我是初学者,所以要简单明了地解释事情:)

【问题讨论】:

  • java或编程或gson初学者?
  • 欢迎@Arc,GSON 很流行并且很容易学习。以下是一些开始的参考。 Link1Link2

标签: java json api gson wunderground


【解决方案1】:

您可以解析整个流,然后提取您需要的内容。下面是一个解析它的例子:

    String url=getUrl();
    JSONObject jsonObject = new JSONObject();
    StringBuilder stringBuilder=new StringBuilder();
    try 
    {
        HttpGet httpGet = new HttpGet(url);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }

        jsonObject = new JSONObject(stringBuilder.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
    } catch (IOException e) {    }

阅读它,您必须在表格中导航,如下所示:

jsonObject.getJSONObject("Results");

这是我使用这个库的一个程序中的一个示例:

int statusCode=jobj.getJSONObject("info").getInt("statuscode");

我大量使用以下内容来正确处理:

jsonObject.names();

这将为您提供所有键的名称。从那里,您必须确定它是数组、对象还是原始类型。我需要一点时间才能把它做好,但是一旦你完成了一次,它就永远完成了,希望如此。在他们的 JSON 库中查看 the Android documents

【讨论】:

    【解决方案2】:

    GSON 可以将 JSON 树解析为 Java 对象,即 Java 类的实例。因此,如果您想在这种情况下使用 GSON,您必须创建类并使用 JSON 结构的相关字段名称对其进行注释。 GSON 有一个非常广泛且易于阅读的documentation,请查看。但是对于这种复杂的树,我不建议将它映射到 Java 对象中。如果您只需要一些数据,请删除 GSON 并按照 PearsonArtPhoto 的建议手动导航树。

    【讨论】:

      【解决方案3】:

      您可以使用JsonParser。这是一个基于您的 url 的示例,您可以立即复制、粘贴和运行。

      我添加了一个实用方法,允许您使用类似路径的方式从生成的JsonElement 树中获取元素。实际上,您的 JSON 几乎是一棵对象和值的树(预测部分除外)。

      请注意,JsonElement 可以根据需要再次“转换”为对象、数组或基值。这就是为什么在调用getAtPath 之后,我调用getAsString 方法。

      package stackoverflow.questions.q19966672;
      
      import java.io.*;
      import java.net.*;
      import java.nio.charset.Charset;
      
      import com.google.gson.*;
      
      public class Q19966672 {
      
              private static String readAll(Reader rd) throws IOException {
      
              BufferedReader reader = new BufferedReader(rd);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line);
              }
              return sb.toString();
          }
      
          private static JsonElement getAtPath(JsonElement e, String path) {
              JsonElement current = e;
              String ss[] = path.split("/");
              for (int i = 0; i < ss.length; i++) {
                  current = current.getAsJsonObject().get(ss[i]);
              }
              return current;
          }
      
          public static void main(String[] args) {
              String url = "http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json";
              InputStream is = null;
              try {
                  is = new URL(url).openStream();
                  BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                  String jsonText = readAll(rd);
      
                  JsonElement je = new JsonParser().parse(jsonText);
      
                  System.out.println("In " + getAtPath(je, "current_observation/display_location/city").getAsString() + " is " + getAtPath(je, "current_observation/weather").getAsString());
      
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
      
              } finally {
                  try {
                      if (is != null)
                          is.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
      
      }
      

      结果如下:

      In Denver is Mostly Cloudy
      

      【讨论】:

        猜你喜欢
        • 2011-10-24
        • 2014-02-12
        • 1970-01-01
        • 2014-04-26
        • 1970-01-01
        • 2012-10-18
        • 2015-05-28
        • 1970-01-01
        • 2018-12-25
        相关资源
        最近更新 更多