loop through android hashmap array - java

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.

Related

How to Traverse Complex JSON and put into a Map?

I tried few days to get this done. but could`t .
What i want is Traverse any given JSON and put Key and Value pair into a map. As a sample consider this JSON
String test = {
"RechargeRequest":{
"RechargeSerialNo":"2645",
"RechargeChannelID":"3",
"RechargeObj":{
"SubAccessCode":{
"PrimaryIdentity":"763500001"
}
},
"RechargeInfo":{
"CashPayment":[
{
"Amount":"30"
}
]
}
}
}
What i have tried so far
JSONObject jsonObj = new JSONObject(test);
Iterator<String> keys = jsonObj.keys();
Map<String,String> map = new HashMap<>();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObj.get(key) instanceof JSONObject) {
}else if(jsonObj.get(key) instanceof JSONArray){
}else{
}
}
Maps value should be like ( "RechargeChannelID","3")
( "Amount":"30")
Can anybody help me please?
Thanks,
If I understood correctly you want to flatten your json file into one level then map it to key and value pairs, kindly check the link below:
How to deserialize JSON into flat, Map-like structure?

Parsing Json file and create Hashmap<k,v>

I am finding a solution for get each single key value of a JSONObject dynamicaly.
I have a JSON file like this:
{
"RESPONSE":{
"A":"test",
"B":{
"C":"0",
"D":"1"
},
"E":{
"F":"2",
"G":"3"
}
}
}
I wish to create a Hashmap that contains the key and the value of the objects, like this example:
legend:
key = value
"A" = "test"
"B" = "{"C":"0", "D":"1"}"
"B.C" = "0"
"B.D" = "1"
"E" = "{"F":"2","G":"3"}"
"E.F" = "2"
"E.G" = "3"
I have tried writing this code:
private static HashMap<String, Object> createJsonObjectsHashMapOfConfigFile(String jsonFilePath,
String JsonObjectToIterate) throws Exception {
HashMap<String, Object> jHashMap = new HashMap<>();
JSONObject jsonConfigFile = SimulatorUtil.readJsonFromFile(jsonFilePath); // Returns the Json file
JSONObject jsonConfigObj = jsonConfigFile.getJSONObject(JsonObjectToIterate); // JsonObjectToIterate -->
// "RESPONSE"
Iterator<?> configIter = jsonConfigObj.keys();
String currentDynamicKey = "";
while (configIter.hasNext()) {
currentDynamicKey = (String) configIter.next();
Object currentDynamicValue = jsonConfigObj.get(currentDynamicKey);
jHashMap.put(currentDynamicKey, currentDynamicValue);
logger.info(" ---> " + jHashMap.toString());
}
return jHashMap;
}
but it get only the first level key ("A", "B", "E").
I must use org.json.
Can anyone help me?
Thanks,
Luca

JSONSimple Overwriting

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.

print values from json file

I'm using the following code to get JSON data from file, currently I was able to achieve the JSON but in one string. I want to parse it to array. The json file is like this:
{
"employee": [
{
"name": "joan",
"lastname": "test",
"age": 23
},
I'm using the following code to get the data but I get it in one string and I want to print some of the data
JSONObject jsonObject = (JSONObject) parser
.parse(new FileReader("C:\\MockData\\Json\\js.txt"));
JSONParser parser1 = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory() {
public List<?> creatArrayContainer() {
return new LinkedList<Object>();
}
public Map<?, ?> createObjectContainer() {
return new LinkedHashMap<Object, Object>();
}
};
Map<?, ?> json = (Map<?, ?>) parser1.parse(jsonObject.toJSONString(), containerFactory);
Iterator<?> iter = json.entrySet().iterator();
System.out.println("==iterate result==");
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
this is the output
employee=[{age=23, name=joan, lastname=test}, {age=22, name=Alex, lastname=avz}, {age=65, name=Dan, lastname=severn}]
Here the entry.getValue() is retuen one concatenated string of the array,
the while is running just one time...
but I want to loop on it to take the key value. How should I do that?
for example if I want to print name alex witn age 22 how should I do that?
Note: The file can be changed so I don't know the keys (now its name but in can be firstName and any other field for that i need generic solution).
if there is a way to use different parser that can do that Im open.
The following is the full solution to your question.
With this code you can break down the data to each employee and also separate the employee attributes.
Set<String> keySet = jsonObject.keySet();
Iterator keySetIterator = keySet.iterator();
while(keySetIterator.hasNext()){
JSONArray array = (JSONArray)jsonObject.get(keySetIterator.next());
while(employeeKeySetIterator.hasNext()){
String employeeKey = employeeKeySetIterator.next().toString();
System.out.println(employeeKey + " : "+ employee.get(employeeKey));
}
}
}
You need to cast the inner json string to a JSONArray
JSONArray array = (JSONArray)jsonObject.get("employee");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toString());
}

Parse JSON object with string and value only

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;

Categories

Resources