Extract JSONObject and iterate through HashMap field - json

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

Related

Convert Json String to ArrayList

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

Swift JSON add new key to existing dictionary

I'm using Alamofire and SwiftyJSON to get and manage data from an API
After making my initial request I end up with nested collection of type JSON
According to SwiftyJSON I can loop through data like so
https://github.com/SwiftyJSON/SwiftyJSON#loop
for (key: String, subJson: JSON) in json {
//Do something you want
}
Again, according to SwiftyJSON I should be able to set new values like so:
https://github.com/SwiftyJSON/SwiftyJSON#setter
json["name"] = JSON("new-name")
I have a nested collection of data and I can dig in as deep as I want, but I'm unable to alter the object and set new key:value pair. How would I got about doing this in Swift?
Here's my code :
for (key: String, stop: JSON) in stops {
var physicalStops = stop["physicalStops"]
for (key: String, physicalStop: JSON) in physicalStops {
println("Prints out \(physicalStop) just fine")
// physicalStop["myNewkey"] = "Somevalue" // DOES NOT WORK (#lvalue is not identical to 'JSON)
// physicalStop["myNewkey"] = JSON("Somevalue") //SAME Story
}
}
Basically I'd like to keep the very same structure of the original JSON object, but add additional key:value on the second level nesting for each sub object.
First, you can use var in for-loop to make value modifiable inside the loop. However, JSON is struct so it behaves as a value type, so in your nested example, you have to reassign also the child JSON to the parent JSON otherwise it just modifies the value inside the loop but not in the original structure
var json: JSON = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key: String, var item: JSON) in json {
println("\(key) -> \(item)")
item["price"] = 10
json[key] = item
}
println(json)
Below is code that runs fine in Swift 2 playground and does not require Swifty:
var json: [String:AnyObject] = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key,item) in json {
print("\(key) -> \(item)")
let newItem = ["price": 10]
json[key] = newItem
}
print(json)

Appending values in a list and then sending as a JSON object

var jsonElements = List[String]()
val params = Map("host"->host)
for((key,value)<-mapSql){
val map = Map("metric"->key,"timestamp"->new Date().getTime,"value"->value,"tags"->params)
jsonElements=JsonUtility.toJSONString(map) :: jsonElements
}
val entity = new StringEntity(JsonUtility.toJSONString(jsonElements))
println("json elements final list is "+jsonElements)
println("json elements final JSON Obj is "+JsonUtility.toJSONString(jsonElements))
entity.setContentType(new BasicHeader("Content-Type", "application/json"))
val postRequest: HttpPost = new HttpPost(putURL)
postRequest.setEntity(entity)
val postResponse: CloseableHttpResponse = httpclient.execute(postRequest)
I basically need to add values to a list and then send them together in a JSON Array.
However this is introducing unnecessary escape characters "/" in the output which is rendering the post request useless and I am getting an error to the API hit. the following is the response :
json elements final list is List({"metric":"replicationLag","timestamp":1410179907871,"value":0.0,"tags":{"host":"tg-em-db01.nm.xxxx.com"}}, {"metric":"status","timestamp":1410179907824,"value":1,"tags":{"host":"tg-em-db01.nm.xxxxx.com"}})
json elements final JSON Obj is ["{\"metric\":\"replicationLag\",\"timestamp\":1410179907871,\"value\":0.0,\"tags\":{\"host\":\"tg-em-db01.nm.xxxx.com\"}}","{\"metric\":\"status\",\"timestamp\":1410179907824,\"value\":1,\"tags\":{\"host\":\"tg-em-db01.nm.xxxxx.com\"}}"]
I can replace and remove all the escape characters by the replaceAll function but I do not want to do that. is there a better way to append objects to an already existing JSON object and then change it to an array ( which i can easily do by new JsonArray(List(JsonObj)) ) so that i dont get any escape characters anywhere.
Something like this :
val params = Map("host"->host)
var map = Map[String,Any]()
for((key,value)<-mapSql){
map ++= Map("metric"->key,"timestamp"->new Date().getTime,"value"->value,"tags"->params)
}
val entity = new StringEntity(JsonUtility.toJSONString(List(map)))
println("json elements final list is "+map)
println("json elements final JSON Obj is "+JsonUtility.toJSONString(List(map)))
is giving me this as an ouput :
json elements final list is Map(metric -> replicationLag, timestamp -> 1410180939983, value -> 0.0, tags -> Map(host -> tg-em-db01.nm.xxxx.com))
json elements final JSON Obj is [{"metric":"replicationLag","timestamp":1410180939983,"value":0.0,"tags":{"host":"tg-em-db01.nm.xxxxx.com"}}]
But I need something like this :
[ {"metric":blah blah} , {"metric":blah blah} ]
Is there a way to append to maps such that the same key values are not clubbed ?
Thanks in advancE!
var jsonElements = List[Map[String, Any]]()
val params = Map("host" -> host)
for ((key, value) <- mapSql) {
val map = Map("metric" -> key, "timestamp" -> new Date().getTime, "value" -> value, "tags" -> params)
jsonElements = map :: jsonElements
}
val entity = new StringEntity(JsonUtility.toJSONString(jsonElements))
entity.setContentType(new BasicHeader("Content-Type", "application/json"))
val postRequest: HttpPost = new HttpPost(putURL)
postRequest.setEntity(entity)
val postResponse: CloseableHttpResponse = httpclient.execute(postRequest)
object JsonUtility {
def toJSONString(obj:Any):String = {
compact(JsonAST.render(decompose(obj)))
}
}

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

how to convert an object from json format to integer format

I am passing an array from view to the controller using json.stringify() method.
That value is passed to the controller and is in
"\"[{\\\"id\\\":1 "id\\\":2}]\"" format. I think this is in json format, I want to convert this into {id:1,id:2} format.
I tried to convert this into string format using JsonConvert.SerializeObject(),
but it is displaying in "\"\\\"[{\\\\\\\"id\\\\\\\":1}]\\\"\"" format.
Can you tell me how can I convert into {id:1,id:2} format/integer format?
The JSON data represents an array containing a dictionary as far as I can tell. You could get hold of a Dictionary representation of the data like this:
var json = "[{\"id\":1, \"id\": 2}]";
Dictionary<string, int>[] obj = JsonConvert.DeserializeObject<Dictionary<string, int>[]> (json);
var dict = obj[0];
I'm not sure if this is what you're after though, since you're saying that you want to display it like {id: 2}. If you want to print it out like that, you can build a string representation of the Dictionary:
var sb = new StringBuilder();
sb.Append("{");
foreach (var item in dict)
{
sb.Append(string.Format("{0}: {1}, ", item.Key, item.Value));
}
sb.Remove(sb.Length - 2, 2);
sb.Append("}");
Console.WriteLine(sb.ToString());
This prints {id: 2}.
To retrieve the value for 'id', if this is what you mean, you can do this:
var val = dict["id"];
var serializer = new JavaScriptSerializer();
var data = serializer.Deserialize<object[]>(jsonString);