I am attempting to iterate through a hash map and create a json string from the values. Im using the JSONSimple library to do so. I have the structure I want, but the values are being overwritten. The structure I am ending up with is
{
"new_id":{
"coordinates_list":{
"Coordinates: ":[
"lat: 27.0",
"lon: 28.0"
]
},
"t0vhf40cv86t":[
"123"
]
}
}
But there should be additional values in the JSON. Only the last row of the hash map is being included. Do I need to add another JSONObject that I write to?
JSONObject obj = new JSONObject(); // final json object written out
double lat = 20.00; // test data
double lon = 21.00; // test data
for (Map.Entry<String, List<String>> entry : data.entrySet()){
JSONObject childObj = new JSONObject();
JSONObject coordObj = new JSONObject();
JSONArray entities = new JSONArray();
JSONArray coordinates = new JSONArray();
String key = entry.getKey();
List<String> values = data.get(key);
for(String value : values){
entities.add(value);
}
childObj.put(key,entities);
// increments the test data
lat = lat +1;
lon = lon + 1;
coordinates.add("lat: " + lat);
coordinates.add("lon: " + lon);
coordObj.put("Coordinates: " ,coordinates);
childObj.put("coordinate list ", coordObj);
obj.put("new_id" , childObj);
}
You are always using "new_id" as the key on the "obj.put" line. For the first map entry, you set the value for that key on the JSON object. For each subsequent entry, you are replacing the value for that key, not adding a new key. That is why only the last entry in the map is represented in the JSON.
I'm not sure exactly what you're trying to accomplish, but you likely either need to use a different key each time through the loop or use a JSONArray instead of a JSONObject so that you don't need keys at all.
Related
I have this code block that iterates over the all keys in my JSONObject, jsonObject1 is a json object that has 1 key and bunch of json data as the value of this single key. So it look like this {"singleKey":"{"anotherKey":"anotherValue"}, {"someKey":"someValue"}"}
JSONObject jsonObject1 = new JSONObject(mystring);
Iterator<String> iter = jsonObject1.keys();
while(iter.hasNext())
{
String key = iter.next();
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(key));
key1 = jsonObject2.getString("key");
value1 = jsonObject2.getString("value");
String place += "\n" + key1 + ": " + value1;
}
What I want is, I want this while loop starts from the last key of the jsonObject2 and iterates over to the first key. So I will start adding to my place string starting from the last value of the jsonObject2. The first value of place string will be someKey: someValue (the last element of the JSONObject).
How can I start this iteration starting from the last key of the json object?
OK, try this (haven't fully tested):
public void jsonMethod(String mystring) throws JSONException {
JSONObject jsonObject1 = new JSONObject(mystring);
Iterator<String> iter = jsonObject1.keys();
ArrayList<String> keySet = new ArrayList<>();
while(iter.hasNext()){
keySet.add(iter.next());
}
Collections.reverse(keySet);
for(String myKey: keySet){
JSONObject jsonObject2 = new JSONObject(jsonObject1.getString(myKey));
// Do your existing stuff with jsonObject2
}
}
Actually I am trying to parse the two api's json data in the same class. I know it should not be done but this is the requirement.
I am getting data from the hashmap. And I want to add it in the table.But the problem is program adds only last item in table. but while debugging it's giving all values.
Here is my code:
public class services2
{
public Map<Object, Object> getReportees(String idOfEmp) throws Exception {
......
if(resp.getStatus() != 200){
System.err.println("Unable to connect to the server");
}
String output = resp.getEntity(String.class);
//Store the JSON objects in an array
//Get the index of the JSON object and print the values as per the index
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(output);
JSONArray jsonarr_1 = (JSONArray) jobj.get("list");
Map<Object, Object> map=new HashMap<Object,Object>();
for(int i=0;i<jsonarr_1.size();i++){
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
JSONObject jive = (JSONObject)jsonobj_1.get("jive");
String var = jive.get("username").toString();
values = var;
if(resp1.getStatus() != 200){
system.err.println("Unable to connect to the server");
}
String output1 = resp1.getEntity(String.class);
JSONObject jobjs = (JSONObject) new JSONParser().parse(output1);
JSONArray jsonarr_11 = (JSONArray) jobjs.get("issues");
System.out.println("count"+jsonarr_11.size());
Object obj3 = jsonarr_11.size();
int counter = (Integer) obj3;
System.out.println(counter);
Object obj1 = jsonobj_1.get("displayName");
Object obj2 = jive.get("username");
map.put(obj1, obj2);
map.put("obj3", obj3);
System.out.println(obj3);
}
return map; //for the map obj3 return only the last count that is 1
}
}
Here when I am trying to send the map obj3. I am getting only the last value. I actually want the count in a correct way.
This is the output:
Number id username count
1 A12345 Anagha R 1
2 M12345 Madhusudan S 1
3 AT12345 Amreen Taj 1
Expected output is:
1 A12345 Anagha R 0
2 M12345 Madhusudan S 0
3 AT12345 Amreen Taj 1
When I am trying to print in the console it is giving me the right count but when I am trying through the map it is sending only the last value that is count 1.
You can try using a list of a map like the following:
List<HashMap<Object,Object>>
The problem is in below line of code:
map.put("obj3", obj3);
Each time you are replacing the value for "Obj3" instead of incrementing the existing value of the map.
Instead what you need to do is:
if(map.containsKey("obj3")
{
Object obj3 = map.get("obj3");
//put your logic of incrementing or adding the count
//Lets say it is new Value
map.put("obj3",newValue)
}
I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :)
here i have parsed allready my json
JSONObject jsonObject = new JSONObject(adresUrl);
JSONArray offerResources = jsonObject.getJSONArray("offerResources");
for(int y = 0; y < offerResources.length(); y++){
JSONObject currentTransfer = offerResources.getJSONObject(y);
JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints");
for (int i = 0; i < meetPoint.length(); i++){
JSONObject currentMeetPoints = meetPoint.getJSONObject(i);
String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how
// here is a litle piece of my json :)
"meetPoints": [
{
"startAddress": "....", // after the collon i have to put my value .
"startLocation": {
thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints.
Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists.
String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" },
{ \"Country\":\"value\", \"state\":\"value\"}]}";
JSONObject meetPoints = new JSONObject(jsonDataString);
JSONObject jsonValueObject = new JSONObject();
JSONArray list = new JSONArray();
jsonValueObject.put("Country", "newValue");
jsonValueObject.put("state", "newValue");
jsonValueObject.put("city", "Chennai");
jsonValueObject.put("street", "Bharathiyar Street");
jsonValueObject.put("date", "14May2017");
jsonValueObject.put("time", "10:00AM");
list.put(jsonValueObject);
meetPoints.accumulate("values", list);
System.out.println(meetPoints);
I've got my php code:
<?php
require('conn.php');
$json = array();
$newquery = "SELECT * FROM absent";
$newresult = mysqli_query($conn, $newquery);
$jsonData = array();
while ($array = mysqli_fetch_array($newresult)) {
array_push($jsonData,array(
"username"=>$array['username'],
"date"=>$array['date']
));
}
echo json_encode(array("result"=>$jsonData), true);
mysqli_close($conn);
?>
and it returned :
{"result":[{"username":"verarmond","date":"2016-11-17"},{"username":"henk","date":"2016-11-15"}]}
How can i get only usernames and only dates in android ??
Thanks and regard.
HashMap is a data structure based on (key, value) pairs.
So, when you do this:
map.put("iOS", "100");
map.put("Android", "101");
You put the value "100" at "iOS" key, and value "101" at "Android" key.
If you want to access this values, you simply use the "map" object and get the value by the key, like this:
String val1 = map.get("iOS"); //this returns "100"
String val2 = map.get("Android"); // this returns "101"
To get all the entries from a map:
ArrayList<String> values = new ArrayList<>();
for (
Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String Value = entry.getValue();
values.add(Value); //this will add all the values in the hashmap into `values` arraylist
}
It is very easy, you can do it by translating your JSON result to a JSON object with:
JSONObject jsonResult = new JSONObject(jsonString);
Then take your JSON array named result:
JSONArray jsonResultArray = new JSONArray(jsonResult.getJSONArray("result"));
Now you can iterate through your JSON Array to get the required elements:
for(JSONObject jsonObject:jsonResultArray) {
Log.d("TAG", "User: " + jsonObject.getString("username"));
Log.d("TAG", "Date: " + jsonObject.getString("date"));
}
You should know that every { means a JSONObject and the [ means a JSONArray, wit that you should have enough to go.
I wrote the code on the fly and can't check it now, maybe there are some typo or error.
I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:
{"1":"sql", "2":"android", "3":"mvc"}
Thank
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;