Sarthak Sarthak - 2 months ago 6
JSON Question

Java- Convert String Value to Integer

I am getting the json data from an API as String but I want to store it in DB and use it as integer. For example I am getting A=15K or 15M but I want 15000.

Here is my class

public class JsonRestApi {
public JsonRestApi() {
try {
String Response = "{\"Youtube Data\":{\"Views\":\"15K\"}}";

JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(Response);

JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject3 = (JSONObject)jsonObject.get("Youtube Data");

String yviews = (String)jsonObject3.get("Views");
System.out.println(yviews);
}
}
}
}


Output- 15K

But I want output as 15000.
However I do not want to change my Json data.
How should I accomplish this?

Answer

Replace K, M etc. with the appropriate number of zeroes.

String yviews = (String)jsonObject3.get("Views");
yviews = yviews.replace( "K", "000").replace( "M", "000000");
System.out.println(yviews);

Edit: If your number of views can have floating point numbers, you can use the following code:

String[][] conversionMatrix = {{"K", "1000"}, {"M", "1000000"}, {"B", "1000000000"}};

for( int i = 0; i < conversionMatrix.length; i++)
{
    if( yviews.endsWith( conversionMatrix[i][0]))
    {
        BigDecimal temp = new BigDecimal( yviews.substring( 0, 
                                            yviews.indexOf( conversionMatrix[i][0])));
        temp = temp.multiply( new BigDecimal( conversionMatrix[i][1]));
        yviews = temp.toBigInteger().toString();
        break;
    }
}

System.out.println( yviews);