简体   繁体   中英

How to handle empty strings in JSON data through an Overlay Type

I've managed to get an array of JavaScriptObjects but sometimes an object's field has an empty string in it, when it should be a double.

My methods in my overlay type are similar to these.

//JSNI methods to get stock data.
 public final native double getPrice() /*-{ return this.price; }-*/;
 public final native double getChange() /*-{ return this.change; }-*/;

If the field is indeed a double then the JavaScriptObject returns it.

When I call getPrice() on a JavaScriptObject when there is an empty string field I get a exception.

How and where should I handle this?

Example Data: { "Year" : 1881, "Annual Mean" : -0.2, "5 yr Mean" : "" }, { "Year" : 1882, "Annual Mean" : -0.26, "5 yr Mean" : -0.27 },

Note: This part of my program is based heavily on

http://code.google.com/webtoolkit/doc/latest/tutorial/JSON.html http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html

Well, if it's an empty string "" , then it can't be converted into a double type. You have got to handle it in your JSNI method (obviously it's up to you to decide what you want to return from the getXXX() method if the JSON value is "" , but let's assume you want to return 0. Then your getter should look like this:

public final native double getPrice() /*-{ return this.price === "" ? 0 : this.price; }-*/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM