'what is difference between having quote and not having quote in json string
Got a string with key/value pair and some one in it having quote (the quote should be kept as part of the string). Would like to parse the key/value pair into a map.
So use JSONObject(inputString)
to construct a JSONObject from source string, then build the map from it.
(using org.json.JSONObject with Android api 31)
String theStr = "{
mKey1:mVal1,
mKey2:\"mVal2\",
\"mKey3\":\"mVal3\"}";
after call the
val map = jsonStrToMap(theStr)
to generate the map from the string, the quote is lost at calling
val jObject = JSONObject(inputString)
to covert to the JSONObject.
The trace log:
inputString: ({mKey1:mVal1,mKey2:"mVal2","mKey3":"mVal3"}),
jObject = JSONObject(inputString) => {"mKey1":"mVal1","mKey2":"mVal2","mKey3":"mVal3"}
+++ jObject.getString(mKey1) ==> mVal1
+++ jObject.getString(mKey2) ==> mVal2
+++ jObject.getString(mKey3) ==> mVal3
return map: {mKey3=mVal3, mKey2=mVal2, mKey1=mVal1}
the function using the JSONObject:
fun jsonStrToMap(inputString: String?): HashMap<String, String> {
val map = HashMap<String, String>()
try {
val jObject = JSONObject(inputString)
System.out.println("\ninputString: ($inputString),\njObject = JSONObject(inputString) => $jObject")
val keys = jObject.keys()
while (keys.hasNext()) {
val key = keys.next()
val value = jObject.getString(key)
System.out.println("+++ jObject.getString($key) ==> $value ")
map[key] = value
}
} catch (e: Exception) { }
return map
.also {
System.out.println("return map: $it")
}
}
Question: How to keep the quote with the string when using JSONObject(inputString)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|