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
Related
I have a json string and need to create an ArrayList where array values have to be inserted in the index position according with the ID value in the json string.
This is an example of the json String:
{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}
I use this code:
List<String> clientsArray = new ArrayList<String>();
String JsonR = '{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}';
JSONObject lJSONObject = new JSONObject(JsonR);
JSONArray lJSONArray = lJSONObject.getJSONArray("clients");
for (int i = 0; i < lJSONArray.length(); i++)
clientsArray.add(Integer.valueOf(lJSONArray.getJSONObject(i).getString("ID")), lJSONArray.getJSONObject(i).getString("Name"));
}
I get this error:
org.json.JSONException: Value {"1":"Client 1","2":"Client 2","3":"Client 3"} at clients of type org.json.JSONObject cannot be converted to JSONArray
Changed this to get the JSONObject:
JSONObject lJSONObject = new JSONObject(JsonR);
for (int i = 0; i < lJSONObject.length(); i++)
{
clientsArray.add(Integer.valueOf(lJSONObject.getString("ID")), lJSONObject.getString("Name"));
}
In PHP:
$jsonArray = array();
while($Row = $Rows->fetch_array(MYSQLI_ASSOC)) {
$RowsArray = array("ID" => $Row['ID'], "Name" => $Row['Name']);
array_push ($jsonArray, $RowsArray);
}
echo json_encode($jsonArray);
Now I get the error:
org.json.JSONException: Value [{"ID":"1","Name":"Client 1"},{"ID":"2","Name":"Client 2"},{"ID":"3","Name":"Client 3"}] of type org.json.JSONArray cannot be converted to JSONObject
It is not a JSONObject now? Why it say it is a JSONArray?
Because this is a JSON Object
{"1":"Client 1","2":"Client 2","3":"Client 3"}
JSON Array should be like this
[{"1":"Client 1","2":"Client 2","3":"Client 3"}]
This is an example for you but this is a wrong JSON Array.
Whats wrong? How to fix?
You are trying to convert JSON objects to JSON Array. And also another problem. Your JSON Object does not contain these objects ID and Name. Need to fix it like this {"clients":[{"id":1,"name":"Client 1"},{"id":2,"name":"Client 2"},{"id":3,"name":"Client 3"}]}
I am trying to save a value to a jsonb DB column:
val deliveryAddressAsJson = deliveryAddress?.toJson()
val lat = deliveryAddressAsJson?.get("latitude")
val lng = deliveryAddressAsJson?.get("longitude")
val dataJson = jsonObject("comment" to "KARTKOORD:#LE#$lat#$lng# #")
val values = mapOf(
"type" to EventType.RESOLVED.dbName,
"created_by" to ctx.userId,
"data" to dataJson.toPgObject(),
"package_id" to packageId
)
#Language("PostgreSQL")
val sql = """insert into package_event(type, created_by, data, package_id) values (:type, :created_by, :data, :package_id)""".trimMargin()
insert(ctx, sql, values).bind()
I can see that the data is saved like this:
data -> {Collections$SingletonMap#6348} size = 1
key = "data"
value = {Collections$SingletonMap#6348} size = 1
key = "comment"
value = "KARTKOORD:#LE#59.8098962#10.7809297# #"
But, if I try to parse it:
val resolvedPackageEvent = fetchRows(ctx, queryOf("select * from package_event where package_id = ? and type = 'resolved'", packageId)).first()
val data = parseJson(resolvedPackageEvent.string("data"))
val deliveryAddress = data.get("comment")
I get an exception thrown:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 20 path $.comment
If I try to get the value with jsonObject method like this:
fun Entity.jsonObject(key: String): JsonObject = when (val v = this[key]) {
is String -> parseJson(v)
else -> v as JsonObject
}
resolvedPackageEvent.jsonObject("data")
I get an exception:
java.lang.ClassCastException: class java.util.Collections$SingletonMap cannot be cast to class com.google.gson.JsonObject (java.util.Collections$SingletonMap is in module java.base of loader 'bootstrap'; com.google.gson.JsonObject is in unnamed module of loader 'app')
How should I parse this json string?
Your data is not an String. As you can see in the debugger, your data is something like
{
"data": {
"comment": "KARTKOORD:#LE#59.8098962#10.7809297# #"
}
}
I don't have the gson syntax at hand, so I can't provide precise code for retrieving the value. You can probably do something like
val result: JsonObject = parseJson(resolvedConsignmentEvent)
val data: JsonObject = result.get("data")
val deliveryAddress: String = data.get("comment")
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")
}
I am trying to iterate through a value (that is a hashMap) of a JSONObject.
First I get a server response that is a String.
Then I turn it into a String! like this:
val responseString = response.serverResponse
Then I turn it into a JSONObject like this:
val jsonObj = JSONObject(responseString.toString()).get("data")
I do the second step because I only want to keep the LinkedHashMap shown in the picture attached.
But the second step returns type "Any" and then I cant iterate through the LinkedHashMap
JSONObject myjsonObject = new JSONObject();
Iterator keyvalues = jsonObject.keys();
while(keys.hasNext()) {String key = keyvalues.next();
if (myjsonObject.get(key) instanceof myjsonObject) {
}
}
I am trying to parse some JSON objects which is made just of (string,string) pairs. The file I am parsing contains this. I want ot emulate resjson behaviour.
{
"first_key": "first_value",
"unicode": "\u0040 #"
}
What I do is
string path = #"d:\resjson\example.resjson";
string jsonText = File.ReadAllText(path);
IDictionary<string, string> dict;
try
{
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonText);
}
catch(Exception ex)
{
// log or something
}
When I obtain the dict object, the
foreach (var pair in _dict)
{
string key = pair.Key;
string value = pair.Value;
Console.WriteLine("Key = '{0}', Value = '{1}'", key, value);
}
This inputs for me :
"Key = 'first_key', Value = 'first_value'"
"Key = 'unicode', Value = '# #'"
Once Newtonsoft.Json deserializes the object, I lose the "\u0040" string and I have no way of knowing how the original file looked like. Is there a way to preserve character escaping ?
Well, one simple idea would be to escape all the backslashes in the original text before passing it to the parser:
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(
jsonText.Replace(#"\", #"\\"));
Using Newtonsoft.Json, you can actually do:
var settings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
var json = JsonConvert.SerializeObject([obj or JToken], settings);
It won't show the original string as that is lost when deserializing, but it will encode all non ascii characters as \uXXXX