Skip to content

Commit

Permalink
#23 fix number parsing bug (#24)
Browse files Browse the repository at this point in the history
* #23 fix number parsing bug

Co-authored-by: Ilya <nagibatr777>
  • Loading branch information
nice2h8u authored Jan 29, 2022
1 parent 6b1359f commit 97759ba
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public Double toJson(@NoneableDouble Double l) {
@FromJson
@NoneableDouble
public Double fromJson(String s) {
return s.equalsIgnoreCase("none") ? null: Double.valueOf(s);
return Parser.getNumberFromString(s, Double::parseDouble);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public Long toJson(@NoneableLong Long l) {
@FromJson
@NoneableLong
public Long fromJson(String s) {
return s.equalsIgnoreCase("none") ? null: Long.valueOf(s);
return Parser.getNumberFromString(s, Long::parseLong);
}

}
11 changes: 11 additions & 0 deletions src/main/java/com/crazzyghost/alphavantage/parser/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
* @author crazzyghost
Expand Down Expand Up @@ -62,4 +63,14 @@ public static String toJSON(Map<String, Object> data) throws IOException {
Type type = Types.newParameterizedType(Map.class, String.class, Object.class);
return moshi.adapter(type).toJson(data);
}

public static <N extends Number> N getNumberFromString(String s, Function<String, N> parser) {
N result = null;
try {
result = parser.apply(s);
} catch (NumberFormatException ex) {
}

return result;
}
}
34 changes: 34 additions & 0 deletions src/test/java/parser/ParserUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package parser;

import com.crazzyghost.alphavantage.parser.Parser;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class ParserUtilTest {

@Test
public void testGetLongFromString() {
long actualNum = Parser.getNumberFromString("1", Long::parseLong);
assertEquals(1L, actualNum);
}

@Test
public void testGetLongFromNotNumberString() {
Long actualNum = Parser.getNumberFromString("-", Long::parseLong);
assertNull(actualNum);
}

@Test
public void testGetDoubleFromString() {
double actualNum = Parser.getNumberFromString("-1.2312342342", Double::parseDouble);
assertEquals(-1.2312342342, actualNum, 0.0);
}

@Test
public void testGetDoubleFromNotNumberString() {
Double actualNum = Parser.getNumberFromString("-", Double::parseDouble);
assertNull(actualNum);
}
}

0 comments on commit 97759ba

Please sign in to comment.