【问题标题】:Use JSON in Java在 Java 中使用 JSON
【发布时间】:2017-05-08 04:35:53
【问题描述】:

我是初学者。我想编写一个天气应用程序,从网络上获取一些信息并将其展示给用户。但是我无法将用户输入传递给 JSON 方法。有谁能够帮我? 问题出在 ActionListener 部分。

import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;

public class Weather extends JFrame implements ActionListener {
    static JButton getWeather;
    static JTextField inputZip, showCity, showState, showCondition, showTemp;
    static JLabel enterZip, city, state, condition, temp, image;
    public static double temp_f, temp_c;
    static Image pic;
    public static String zip, jCity, jState, jCondition, fORc;

    public Weather() throws Exception {
       //Button
        getWeather = new JButton("Get Weather");
        getWeather.addActionListener(this);
        //TextFiels
        inputZip = new JTextField(10);
        showCity = new JTextField(10);
        showState = new JTextField(10);
        showCondition = new JTextField(10);
        showTemp = new JTextField(10);
        //Labels
        enterZip = new JLabel ("Enter Zipcode:");
        city = new JLabel ("City:");
        state = new JLabel ("State:");
        condition = new JLabel ("Condition:");
        temp = new JLabel ("temp:");
        //Radio Buttons
        CheckboxGroup tUnit = new CheckboxGroup();
        Checkbox f = new Checkbox ("f", tUnit, true);
        Checkbox c = new Checkbox ("c", tUnit, false);
        //Image
        URL coldPicURL = new URL("https://cdn1.iconfinder.com/data/icons/xmas-color/512/snow_snowflake_winter_cold_weather-128.png");
        URL hotPicURL = new URL("http://yowindow.com/img/yo_128.png");
        URL picURL = new URL ("http://findicons.com/files/icons/2796/metro_uinvert_dock/128/the_weather_channel.png");
        if (temp_f!=0 && temp_f<=60)
            pic = ImageIO.read(coldPicURL);
        else if (temp_f > 60)
            pic = ImageIO.read(hotPicURL);
        else 
            pic = ImageIO.read(picURL);  
        image = new JLabel(new ImageIcon(pic));
        //Frame
        JFrame weather = new JFrame ("Weather App");
        weather.setVisible(true);
        weather.setSize(500,250);
        weather.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Panels
        JPanel pInput = new JPanel();
        JPanel pDisplay = new JPanel();
        JPanel pDisplayInfo = new JPanel();
        JPanel pTempUnits = new JPanel();
        JPanel pImage = new JPanel();
        //Panels' Layout
        pInput.setLayout(new FlowLayout());
        pDisplay.setLayout(new BorderLayout());
        pDisplayInfo.setLayout(new GridLayout(5,2));
        pTempUnits.setLayout(new FlowLayout());
        //Frame Layout
        weather.add(pInput, BorderLayout.NORTH);
        weather.add(pDisplay, BorderLayout.CENTER);
        pDisplay.add(pDisplayInfo, BorderLayout.NORTH);
        pDisplay.add(pTempUnits, BorderLayout.CENTER);
        weather.add(pImage, BorderLayout.EAST);
        //Insertion the objects into the panels
        pInput.add(enterZip);
        pInput.add(inputZip);
        pInput.add(getWeather);
        pDisplayInfo.add(city);
        pDisplayInfo.add(showCity);
        pDisplayInfo.add(state);
        pDisplayInfo.add(showState);
        pDisplayInfo.add(condition);
        pDisplayInfo.add(showCondition);
        pDisplayInfo.add(temp);
        pDisplayInfo.add(showTemp);
        pTempUnits.add(c);
        pTempUnits.add(f);
        pImage.add(image);
    }

    public void actionPerformed(ActionEvent e) {
        zip = Weather.inputZip.getText();
        //HERE'S WHERE I'M STUCKED !!! :(
        getJson (zip);
        showCity.setText(jCity);
        showState.setText(jState);
        showCondition.setText(jCondition);
        if (fORc.equals("f"))
        showTemp.setText(Double.toString(temp_f));
        if (fORc.equals("c"))
        showTemp.setText(Double.toString(temp_c));
    }

    public static void getJson(String zip) throws Exception  {
        String json="", line;
        JsonElement jse;
        final String key = "7b86aadc43344a90";
        JsonParser parser = new JsonParser();
        URL url = new URL("http://api.wunderground.com/api/" +
            key + "/conditions/q/" + zip + ".json");
        InputStream is = url.openStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        while ((line = rd.readLine()) != null)
            json += line;
        rd.close();
        jse = parser.parse(json);
jCity=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("city").getAsString();
        jState=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("state").getAsString();
    jCondition=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("weather").getAsString();
        temp_f=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_f").getAsDouble();
        temp_c=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_c").getAsDouble();
    }   

    public void itemStateChanged (ItemEvent ie){
        Checkbox cb = (Checkbox)ie.getItemSelectable();
        fORc = cb.getLabel();
    }

    public static void main(String[] args) throws Exception {
        Weather w = new Weather();
    }
}

【问题讨论】:

  • 使用 Gson 怎么样
  • 1) “谁能帮帮我?” Why is “Can someone help me?” not an actual question? 2) “问题出在 ActionListener 部分”代码语句?你期望结果是什么?为了提供帮助,我们将需要更多详细信息。
  • 我希望 ActionListener 从 textField 获取 zip 并将其提供给 getJson (zip) 并显示结果!但事实并非如此!
  • 错误是:“未报告的异常java.lang.Exception;必须被捕获或声明被抛出”
  • 当我抛出异常时,会出现另一个错误:“天气中的 actionPerformed(java.awt.event.ActionEvent) 无法在 java.awt.event 中实现 actionPerformed (java.awt.event.ActionEvent)。 ActionListener 被覆盖的方法不会抛出 java.lang.Exception"

标签: java json swing jframe actionlistener


【解决方案1】:

在第一层:

getJson (zip);

该调用引发异常。在 Java 中,您必须尝试/捕获该异常;或将其添加到发生这种情况的方法的签名中(使用 throws 关键字)。在您的情况下,这是不可能的,因为您实际上是在覆盖现有方法;然后你不能添加 throws 语句到方法签名中。

但这里真正的答案是:。上面的编译器错误是关于 Java 中的 super basic 的。如果您不知道什么是异常以及如何正确处理它,那么您距离编写一个想要处理来自远程的 JSON 数据的 Swing UI 应用程序还有很多时间学习网站。

在查看您的代码结构时,这一点也变得很明显。您明确区分职责;你围绕那些帮助你提出一个干净的基于 OO 的模型创建类。例如,您可以完全将显示信息的 UI 层(swing)与此类信息的来源细节分开。您的 JFrame 不应该知道关于 JSON 输入的任何事情

您的代码没有显示任何内容。我称之为“你应该在参加跨栏比赛之前学会爬行”综合症。

【讨论】:

    【解决方案2】:

    首先,我认为您最好提供更详细的信息,这是什么问题?这种意外结果是例外吗?或者您可以将结果发布给其他人查看。

    其次,我尝试运行您的程序。这里面有两个问题。 1. 在您写评论的代码中://HERE'S WHERE I M STUCKED !!! :(

    zip = Weather.inputZip.getText();
        //HERE'S WHERE I'M STUCKED !!! :(
        getJson (zip);
        showCity.setText(jCity);
        showState.setText(jState);
    

    getJson()方法你有“抛出异常”,所以当你调用方法时,你还需要处理异常,也许你可以像这样捕获异常:

            zip = Weather.inputZip.getText();
        //HERE'S WHERE I'M STUCKED !!! :(
        try {
            getJson (zip);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        showCity.setText(jCity);
        showState.setText(jState);
    

    或者你可以继续抛出异常。

    1. 完成上一个问题后,我发现“fORc”会遇到空指针异常,您需要检查您的进程何时传递var。

    第三,还是关于 fORc,在你的代码中,你写了

    if (fORc.equals("f"))
            showTemp.setText(Double.toString(temp_f));
    if (fORc.equals("c"))
            showTemp.setText(Double.toString(temp_c));
    

    但是我建议你可以这样改,那么当fORc为null的时候你就可以处理了:

        if (null == fORc)
            //do something. like throw exception
        if ("f".equals(fORc))
            showTemp.setText(Double.toString(temp_f));
        if ("c".equals(fORc))
            showTemp.setText(Double.toString(temp_c));
    

    希望能帮到你。

    【讨论】:

    • 谢谢。第一部分得到修复。我不知道 printStackTrace()。第二部分需要更多的工作。不过谢谢。
    • printStackTrace()。只是显示一个简单的方法。您还可以记录或执行其他过程。关键是您需要捕获异常。顺便说一句..为什么我得到“-2票”...
    猜你喜欢
    • 2014-07-25
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2017-03-20
    • 1970-01-01
    相关资源
    最近更新 更多