Home > Enterprise >  Parsing JSON String in Android Studio
Parsing JSON String in Android Studio

Time:10-23

Im trying to convert a String to a JSON Object, but im getting following Error Message

E/JSON Parser: Error parsing data org.json.JSONException: Value {"data":[{"temperaturaussen":12,"feuchtaussen":77.41,"temperaturbadezimmer":21}]} of type java.lang.String cannot be converted to JSONObject

Im getting my Data like this

val url = URL("url")
    val connection : URLConnection = url.openConnection()
    connection.connect()
    val bufferedInputStream = BufferedInputStream(connection.getInputStream())
    val bufferedReader : BufferedReader = bufferedInputStream.bufferedReader(Charsets.UTF_8)
    val stringBuffer = StringBuffer()
    for (line in bufferedReader.readLines()){
        stringBuffer.append(line)
    }
    bufferedReader.close()
    val fullJson : String = stringBuffer.toString()

I know the Json String from the url is valid, as i checked it on https://jsonformatter.curiousconcept.com/, which looks like this

"{\"data\":[{\"temperaturaussen\":12,\"feuchtaussen\":77.41}]}"

but why am i getting this Error Message when i try to convert it into a JSON?

try {
        val dataJson = JSONObject(fullJson)
    } catch (e: JSONException) {
        Log.e("JSON Parser", "Error parsing data $e")
    }

CodePudding user response:

Try using the below code

try {
    val dataJson = new JSONObject(fullJson)
} catch (e: JSONException) {
    Log.e("JSON Parser", "Error parsing data $e")
}

CodePudding user response:

It seems that the JSON you are trying to parse is not a JSON object (i.e. {...}) but merely a JSON string (i.e. "..."), because the quotes seem escaped (i.e. \" instead of ").

For instance this is a valid JSON string, but it is not a valid JSON object:

"{\"data\":[{\"temperaturaussen\":12,\"feuchtaussen\":77.41}]}"

while this is a valid JSON object:

{"data":[{"temperaturaussen":12,"feuchtaussen":77.41}]}
  • Related