GWT使用JsonUtils解析JSON数据



我正在启动一个GWT应用程序,我想在其中解析JSON数据。最终,我会想发送HTTP请求来从服务器检索JSON,但首先,我试图让GWT解析JSON,但我遇到了麻烦。

我已经在上阅读了文档http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html我真的不明白:(

基于这些文档,我编写了一个简单的客户端类:

public class MyWebApp implements EntryPoint {
  private String personJson = "{ "firstName" : "Jimmy", "lastName" : "Webber" }";
  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {
    Customer c = MyWebApp.parseJson(personJson);
    final TextBox customerDetails = new TextBox();
    final TextBox control = new TextBox();
    customerDetails.setText(c.getFirstName());
    control.setText("This is some control text");
    RootPanel.get("customerContainer").add(customerDetails);
    RootPanel.get("control").add(control);
  }
  public static <T extends JavaScriptObject> T parseJson(String jsonStr) {
    return JsonUtils.safeEval(jsonStr);
  }
  static class Customer extends JavaScriptObject {
    // Overlay types always have protected, zero-arg ctors
    protected Customer() {
    }
    // Typically, methods on overlay types are JSNI
    public final native String getFirstName() /*-{ return this.FirstName; }-*/;
    public final native String getLastName() /*-{ return this.LastName;  }-*/;
    // Note, though, that methods aren't required to be JSNI
    public final String getFullName() {
        return getFirstName() + " " + getLastName();
    }
  }
}

它创建了两个文本框,其中一个正确地预先填充了字符串This is some control text,但另一个仍然为空,这是我所期望的Jimmy。我没有犯任何错误。

JSON数据中的大小写似乎错误,导致JSNI映射失败。如果您将"firstName"更改为"firstName",它应该可以工作。

正如您提到的,您必须通过发送HTTP请求来检索数据。我已经对此进行了研究,并为您提供了一个很好的代码。我希望这个代码能帮助你。我使用了下面链接中的jar文件json-simple-1.1.1.jar-谷歌代码

//开始上课PNRAlgorithm公共类PNRAlgorithm扩展JFrame{

//Variable for PNR number
private String pnr = null;
private StringBuilder response = null;

//Constructor
PNRAlgorithm(String pnr) throws IOException
{
    this.pnr = pnr;
    getPnrResponse(pnr,"json");
}
//Method to get response from the JSON file
private  String getPnrResponse(String pnrNo, String format) throws MalformedURLException, IOException 
{
    //Checking If textfield is empty
    if(pnr == null || pnrNo.trim().length() != 10)
    {
        //Some more validations like only numeric are used etc can be added.
        JOptionPane.showMessageDialog(null,"Invalid PNR");
    }
    else
    {
    //requesting the format of file from API
    format = format == null || format.trim().equals("") ? "json" : format;
    //More validations can be added like format is one of xml or json.
    //String endpoint = "http://railpnrapi.com/api/check_pnr/pnr/"+pnrNo+"/format/"+format;
    String endpoint = "http://api.erail.in/pnr?key=API_KEY&pnr="+pnr+"";
    HttpURLConnection request = null;
    BufferedReader rd = null;
    try
    {
        URL endpointUrl = new URL(endpoint);
        request = (HttpURLConnection)endpointUrl.openConnection();
        request.setRequestMethod("GET");
        request.connect();
        rd  = new BufferedReader(new InputStreamReader(request.getInputStream()));
        //string builder to concatenate the string data
        response = new StringBuilder();
        //string to recieve the data one by one
        String line = null;
        //creating the JsonBuilder
        StringBuilder jsonfile = null;
        //loop to recieve the data one by one
        while ((line = rd.readLine()) != null)
        {
            //saving the response from API
             jsonfile = response.append(line + "n");
        }
        String str = jsonfile.toString();
        JSONParser parser = new JSONParser();

        //Map object to get the data from the JSON file
        Map jsonData = (Map) parser.parse(str);
        String status = (String)jsonData.get("status");
        if(status.equals("OK"))
        {
         Map result = (Map) jsonData.get("result");
         String pnrnum=(String)result.get("pnr");
         String train_no=(String)result.get("trainno");
         String train_name=(String)result.get("name");
         String doj=(String)result.get("journey");
         String fcode = (String) result.get("from");
         String tcode = (String) result.get("to");
         String boarding = (String) result.get("brdg");
         String c_pre = (String)result.get("chart");
        //JOptionPane.showMessageDialog(rootPane, no_psngs);
        //JOptionPane.showMessageDialog(rootPane, number);
        ArrayList passengers =new ArrayList();
        passengers.addAll((ArrayList)result.get("passengers"));
        int no_psngs = passengers.size();
        int number = no_psngs;
        String[] sr = new String[number+1];
        String[] b_status= new String[number+1]; 
        String[] c_status= new String[number+1];
        for(int i=0; i<number ;i++)
         {
             Map pssng = (Map) passengers.get(i);
             sr[i] = (i+1) + "";
             b_status[i] = (String) pssng.get("bookingstatus");
             c_status[i] = (String) pssng.get("currentstatus");
         }
        //Constructor of PNRShow frame and sending the required parameters 
        PNRoutput pNRoutput = new PNRoutput( pnrnum,  train_no,  train_name,  doj,  fcode, tcode,boarding,no_psngs,c_pre,sr,b_status,c_status);

        Runner.runnerFrame.remove(this);
        Runner.runnerFrame.add(pNRoutput);
        pNRoutput.setBounds(10, 155, 978, 430);
    }
        else
        {
            JOptionPane.showMessageDialog(null,"PNR Flushed");
        }
    } 
    catch (ParseException ex) 
    {
        Logger.getLogger(PNRAlgorithm.class.getName()).log(Level.SEVERE, null, ex);
    }

最新更新