Parsing JSON String in Android Studio - json

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")
}

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}]}

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

Related

Nested JSON Objects in Kotlin with Volley

I am very new to this as you can probably tell, but i'm trying to parse a JSON url with Volley using Kotlin in Android Studio. The url contains nested Objects, not nested Arrays.
I can display everything inside "questionnaire", but I only want to display "typeOfQuestion". How do i do that?
MainActivity.kt:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
questionTV = findViewById(R.id.idTVQuestion)
answerTV = findViewById(R.id.idTVAnswer)
typeTV = findViewById(R.id.idTVType)
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
loadingPB.setVisibility(View.GONE)
try {
val question: String = response.getString("question")
val answer: String = response.getString("answer")
val typeOfQuestion: String = response.getString("typeOfQuestion")
questionTV.text = question
answerTV.text = answer
typeTV.text = typeOfQuestion
} catch (e: Exception) {
e.printStackTrace()
}
}, { error ->
Log.e("TAG", "RESPONSE IS $error")
Toast.makeText(this#MainActivity, "Fail to get response", Toast.LENGTH_SHORT)
.show()
})
queue.add(request)
}
}
Heres the JSON:
{
"questionnaire": {
"question": "Where do you live?",
"answer": "In the mountains",
"typeOfQuestion": "Informative
}
}
You have object inside another json object.If you need to access field from child object you need to get child jsonObject and then get fields from object.
var questionnaire = response.getJSONObject("questionnaire")
You need to get fields from questionnaire object.Like.
val question: String = questionnaire.getString("question")
val answer: String = questionnaire.getString("answer")
val typeOfQuestion: String = questionnaire.getString("typeOfQuestion")

How to send JSON String with POST using ktor kotlin?

How to add JSON String in the POST request using kotlin and ktor?
Printing it out the Json string read from file or even constructed string with Kotlin in the client, the content looks like JSON.
Still, the server cannot recognize the string as JSON, and when I print it in the server, each double quota is back slashed.
The client obviously adds the back slashes, thus the request is not formatted as it should.
Client Kotlin - Ktor code:
import com.google.gson.*
import io.ktor.client.*
import io.ktor.http.*
...
val client = HttpClient(OkHttp) {
install(JsonFeature) {
serializer = GsonSerializer()
}
}
val fileContent = MyClass::class.java.getResource("myfile").readText()
println("fileContent string = $fileContent")
val out = client.post<String> {
url(url)
contentType(ContentType.Application.Json)
body = fileContent
}
the print out looks like this :
{ "name": "myname", "value": "myvalue" }
but the server (I use hookbin by the way to really print out the data without Jackson conversions) prints out:
{ \"name\": \"myname\", \"value\": \"myvalue\" }
The solution is to pass to the HTTP POST request a JSON object not a String object. They look the same when you print them, but of course they are not equally interpreted by the JVM. So, we have just to parse the string. I use the GSON library.
Add the JsonParser -> parseString method and use its object in the client:
import com.google.gson.JsonParser
val fileContent = MyClass::class.java.getResource("myfile").readText()
println("fileContent string = $fileContent")
var bodyAsJsonObject = JsonParser.parseString(fileContent).asJsonObject
println("bodyAsJsonObject = $bodyAsJsonObject")
val out = client.post<String> {
url(url)
contentType(ContentType.Application.Json)
body = bodyAsJsonObject
}

"Unexpected Character" on Decoding JSON

The following is the code:
static TodoState fromJson(json) {
JsonCodec codec = new JsonCodec();
List<Todo> data = codec.decode(json["todos"]);
VisibilityFilter filter = codec.decode(json['visibilityFilter']);
return new TodoState(todos: data,
visibilityFilter: filter);
}
Error produced by Android Studio:
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
FormatException: Unexpected character (at character 3)
Any idea how to make it work?
This is the output of the Json as produced by Redux.
There's a problem with your code as well as the string you're trying to parse. I'd try to figure out where that string is being generated, or if you're doing it yourself post that code as well.
Valid Json uses "" around names, and "" around strings. Your string uses nothing around names and '' around strings.
If you paste this into DartPad, the first will error out while the second will succeed:
import 'dart:convert';
void main() {
JsonCodec codec = new JsonCodec();
try{
var decoded = codec.decode("[{id:1, text:'fdsf', completed: false},{id:2, text:'qwer', completed: true}]");
print("Decoded 1: $decoded");
} catch(e) {
print("Error: $e");
}
try{
var decoded = codec.decode("""[{"id":1, "text":"fdsf", "completed": false},{"id":2, "text":"qwer", "completed": true}]""");
print("Decoded 2: $decoded");
} catch(e) {
print("Error: $e");
}
}
The issue with your code is that you expect the decoder to decode directly to a List. It will not do this; it will decode to a dynamic which happens to be a List<dynamic> whose items happen to be Map<String, dynamic>.
See flutter's Json documentation for information on how to handle json in Dart.
I don't know if that's the case, but I got a similar error when me JSON looks like this
[
{
...
},
]
and not like this
[
{
...
}
]
The comma was causing the issue.
If Anyone came here and your are using dio package to call http request you need to set responseType to plain
BaseOptions options = new BaseOptions(
baseUrl: "<URL>",
responseType: ResponseType.plain
);
I also have similar type of error, Be make sure that the argument of .decode method shouldn't be empty object.
try {
if(json["todos"].isNotEmpty) {
List<Todo> data = codec.decode(json["todos"]);
}
if(json["todos"].isNotEmpty) {
VisibilityFilter filter = codec.decode(json['visibilityFilter']);
}
}
catch(e) {
print(e);
}
Do try this, hope it will work for you.

Alamofire response contain text before JSON content use it with SwiftyJSON

I'm requesting a JSON object with Alamofire and accessing it with SwiftyJSON.
The response of my request is this :
// JSON webservice ...
[
{
"message":"Please connect"
}
]
As you can see I need to remove the string "// JSON webservice ..." because it is actually not a valid JSON object.
Note that I'm using the .responseString otherwise I could not remove the string part.
So in order to remove the string I'm doing :
let jsonString = data?.stringByReplacingOccurrencesOfString("// JSON webservice ...", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
Now I'm with my String I can do :
var json = SwiftyJSON.JSON(jsonString!)
and I can print the json :
println(json)
BUT whatever I print a value
println(json[0]["message"].string)
is nil.
I finally found myself a solution :
We get our string (data) from the .responseString method
We remove the part that cause the fail of the serialization of the JSON object
We convert our string to NSData and try to serialize our JSON object :
let data = jsonString?.dataUsingEncoding(NSUTF8StringEncoding)
let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray?
Now it should be fine and everything is working when trying to print a value of the JSON object
var json = SwiftyJSON.JSON(jsonData!)
println(json[0]["message"])
It prints the right value.

JSP, Simple JSON - Parsing each key in the dictionary

I have a JSON dictionary as follows:
JSONObject jsonColMap = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
I want to loop this in JSP such that I can do a for each key in this dictionary, do something. I tried to do the following but I run into an error:
aWF = (JSONObject) jsonParser.parse(request.getParameter("data"));
Set<String> entries = jsonColMap.entrySet();
Iterator<String> iter = entries.iterator();
while(iter.hasNext())
{
String key = iter.next().toString();
if(aWF.containsKey(key))
{
//do something
}
}
But this throws an error
java.util.HashMap$EntrySet cannot be cast to java.util.HashMap
What am I doing wrong ?
EDIT: It complains at the line where entries is created and assigned