Home > Mobile >  JSON-Simple java.lang.String cannot be cast to java.lang.Number
JSON-Simple java.lang.String cannot be cast to java.lang.Number

Time:12-21

I'm trying to get the LAT/LNG values from my json(as Double) seen here:

{
    "placeNames": [
        {
            "name": "Test",
            "lat": "0",
            "lon": "0"
        },
        {
            "name": "Üsküdar Bağlarbaşı Yolu",
            "lat": "1",
            "lon": "2"
        },
        {
            "name": "Çamlıca",
            "lat": "3",
            "lon": "4"
        }
    ]
}

And put markers on location in google maps seen here:

JSONParser jsonParser = new JSONParser();

try {
    JSONObject jsonObject = (JSONObject) jsonParser.parse(GetJson(getContext())); //TODO: READ JSON FILE
    JSONArray lang = (JSONArray) jsonObject.get("placeNames");
    for (int i = 0; i < lang.size(); i  ) {
        JSONObject explrObject = (JSONObject) lang.get(i);
        String PlaceName = (String) explrObject.get("name");
        MarkerOptions marker3 = new MarkerOptions();
        Double LAT = ((Number) explrObject.get("lat")).doubleValue();
        Double LNG = ((Number) explrObject.get("lon")).doubleValue();
        marker3.position(new LatLng(LAT, LNG)).title(PlaceName);
    }
}

The problem im getting is the fact that LNG/LAT values seem to be coming in as string even though theyre numbers on my JSON file,Any help is appreciated.:)

CodePudding user response:

Maybe you can try:

Double LAT = Double.parseDouble(explrObject.getString("lat"));

or

Double LAT = Double.parseDouble((String) explrObject.get("lat"));

CodePudding user response:

Why do you have "lat" and "long" values in double quotes in your json? Have you tried without double quotes in your json file?

CodePudding user response:

Following is a valid JSON syntax with double/ float values that you can use to construct your json as,

{
    "placeNames":[
        {
            "name":"Test",
            "lat":29.470237,
            "lon":107.722125
        }
    ]
}

also, you can refer to this website for validating your JSON syntax online in case of any doubts. And also, your above JSON parser logic will work on this JSON data.

  • Related