GWT 使用 JsonUtils 解析 JSON 数据
GWT parsing JSON data with JsonUtils
我正在启动一个 GWT 应用程序,我想在其中解析 JSON 数据。最终,我想发送 HTTP 请求以从服务器检索 JSON,但首先,我试图让 GWT 完全解析 JSON,但我遇到了麻烦。
我已经阅读了 http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html 上的文档,但我不是很明白 :(
根据文档,我写了这个简单的客户端class:
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();
}
}
}
它创建了 2 个文本框,其中一个正确地预填充了字符串 This is some control text
,但另一个仍然是空的,这正是我所期望的 Jimmy
。我没有收到任何错误。
正如您提到的,您必须通过发送 HTTP 请求来检索数据。
我已经着手解决这个问题,并为 you.I 编写了一个很好的代码,希望这段代码对您有所帮助。
我使用了下面 link 中的 jar 文件
json-simple-1.1.1.jar - Google 代码
//开始class PNR算法
public class 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);
}
好像是JSON数据中的大小写错误,导致JSNI映射失败。如果将 'firstName' 更改为 'FirstName',它应该可以工作。
我正在启动一个 GWT 应用程序,我想在其中解析 JSON 数据。最终,我想发送 HTTP 请求以从服务器检索 JSON,但首先,我试图让 GWT 完全解析 JSON,但我遇到了麻烦。
我已经阅读了 http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsOverlay.html 上的文档,但我不是很明白 :(
根据文档,我写了这个简单的客户端class:
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();
}
}
}
它创建了 2 个文本框,其中一个正确地预填充了字符串 This is some control text
,但另一个仍然是空的,这正是我所期望的 Jimmy
。我没有收到任何错误。
正如您提到的,您必须通过发送 HTTP 请求来检索数据。 我已经着手解决这个问题,并为 you.I 编写了一个很好的代码,希望这段代码对您有所帮助。 我使用了下面 link 中的 jar 文件 json-simple-1.1.1.jar - Google 代码
//开始class PNR算法 public class 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);
}
好像是JSON数据中的大小写错误,导致JSNI映射失败。如果将 'firstName' 更改为 'FirstName',它应该可以工作。