I'm trying to write a cordova plugin.
I've the following JSON data:
JSONObject obj = {"amount":100, "desc":"blabla",id:123}
and I'm trying to iterate the JSON keys and put keys and values to intent.putExtra(key,val)
Example:
Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
key = iter.next();
value = obj.getString(key);
intent.putExtra(key, value);
}
With this code I get the error
error: cannot find symbol intent.putExtra(key, value);
Anyone can say me how correct iterate JSON data and execute putExtra()?
First, the json you provide is not valid. It should be something like:
{"amount":100, "desc":"blabla","id":123}
Then, as said in the comments, create an intent variable outside the for loop.
And finally, you should use
Object value = obj.get(key)
because values can be Strings or Integers.
Extension to Lino's answer.
As Intent.putExtra(String, Object) is not available, you need following modifications.
JSONObject obj = new JSONObject("{" +
"\"amount\": 100," +
"\"desc\": \"blabla\"," +
"\"id\": 123," +
"\"id2\": 123.56" +
"}");
Intent intent = new Intent();
Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = obj.get(key);
if (value instanceof Float || value instanceof Double) {
intent.putExtra(key, (double) value);
} else if (value instanceof Integer || value instanceof Long) {
intent.putExtra(key, (long) value);
} else if (value instanceof String) {
intent.putExtra(key, (String) value);
} /*else if (more cases go here) {
} */
}
Related
I have Json like this:
{
"_id" : ObjectId("5e99f6d16cbddf7dad26557f"),
"channel_id" : 49066,
"timestamp" : NumberLong(1580982302003),
"values" : {
"some id" : "81151501",
"some title" : "Some title",
"some address" : "https://www.some-address.com",
"new hash" : {
"some value" : "5",
"other value" : " 54.10 BRL"
},
"wrong values" : "This text have wrong & values & and netx is wrong too & and this &"
},
"null value" : null,
"zero integer" : 0
}
I need to loop through each key and replace spaces with snake_case, for example from other value to other_value
Additionally, I wanted to check every value in the loop by replacing the character & with _, for example:
from This text have wrong & values & and netx is wrong too & and this & to This text have wrong _ values _ and netx is wrong too _ and this _
My json object is made from:
JSONobject jsonObject = new JSONobject(jsonString)
You could iterate over the keys, normalize the key and recursively continue as long as the value is a JSONObject. If it's not, then you could normalize the value as well. So this would look something like this:
static JSONObject normalize(JSONObject object) throws JSONException {
JSONObject result = new JSONObject();
Iterator iterator = object.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String normalizedKey = key.replace(" ", "_");
Object inner = object.get(key);
if (inner instanceof JSONObject) {
result.put(normalizedKey, normalize((JSONObject) inner));
} else if (inner instanceof String) {
result.put(normalizedKey, object.getString(key).replace("&", "_"));
} else {
result.put(normalizedKey, inner);
}
}
return result;
}
Latest version of the library also provides the ability to obtain a keyset, which would allow for a slightly cleaner looping of the keys:
static JSONObject normalized(JSONObject object) {
JSONObject result = new JSONObject();
object.keySet().forEach(key -> {
String normalizedKey = key.replace(" ", "_");
Object value = object.get(key);
if (value instanceof JSONObject) {
result.put(normalizedKey, normalized((JSONObject) value));
} else if (value instanceof String) {
result.put(normalizedKey, ((String) value).replace("&", "_"));
} else {
result.put(normalizedKey, value);
}
});
return result;
}
I am struggling with a specific problem, that I cannot think of correctly. The following is the problem
I have a map with key value like the following, i just used strings here
String key = "activate.message.success"
String value = "success"
String key1 = "activate.title"
String value1 = "Good Title"
String key2 = "activate.message.error"
String value2 = "error"
String key3 = "activate.message.short.poll"
String value3 = "This is short poll"
I need to build a json like the following
{
"activate":{
"message":{
"success":"success",
"error":"error",
"short":{
"poll":"This is short poll"
}
},
"title":"Good Title"
}
}
I could not think of a proper solution for this use case and struggling for 3 hours. I thought of using recursion, but i dont how exactly i could do. Please help with this. I am using java for this, I should use generic JSONObject to solve as there is not POJO mappings. So far I have just splitted the strings using separtor and stored in an another map like the following
public Map<String, Object> getJsonObjectFromKeyValueMap(Map<String, String> stringValueMap,
Map<String, Object> stringObjectMap) {
for (Entry entry : stringValueMap.entrySet()) {
String[] keyValueArrayString = entry.getKey().toString().split("\\.");
int sizeOfMap = keyValueArrayString.length;
int i = 0;
String concatString = "";
for (String processKey : keyValueArrayString) {
if (i < sizeOfMap - 1) {
concatString += processKey + ".";
stringObjectMap.put(concatString, (Object) new JSONObject());
} else {
concatString += processKey;
stringObjectMap.put(concatString, entry.getValue());
concatString = "";
}
i++;
}
}
return stringObjectMap;
}
First, let's update your data into a proper map :
Map<String, String> data = new HashMap<>();
data.put("activate.message.success", "success");
data.put("activate.title", "Good Title");
data.put("activate.message.error", "error");
data.put("activate.message.short.poll", "This is short poll");
Then, your logic is pretty close, for each node but the last, you create a new JSONObject, for the last, you insert the value.
If you try to build a JSONObject instead of the map directly, you would get a pretty good result already, well somewhat of a result.
The following will iterate a Map<String, String> of data.
For each entry, we split the key to getting the nodes.
Then, we just need to move in the json, if a node doesn't exist, we create it.
Then, for the last value, create the value.
public static JSONObject build(Map<String, String> data) {
JSONObject json = new JSONObject();
//Iterate the map entries
for (Entry<String, String> e : data.entrySet()) {
String[] keys = e.getKey().split("\\.");
// start from the root
JSONObject current = json;
for (int i = 0; i < keys.length; ++i) {
String key = keys[i];
//Search for the current node
try {
//If it exist, do nothing
current = current.getJSONObject(key);
} //If it does not exist
catch (JSONException ex) {
//Is it the last node, create the value
if (i == keys.length - 1) {
current.put(key, e.getValue());
} //Not the last node, create a new JSONObject
else {
JSONObject tmp = new JSONObject();
current.put(key, tmp);
current = tmp; //Always replace current with the last node to go deeped each iteration
}
}
}
}
return json;
}
And the example :
public static void main(String[] args) {
Map<String, String> data = new HashMap<>();
data.put("activate.message.success", "success");
data.put("activate.title", "Good Title");
data.put("activate.message.error", "error");
data.put("activate.message.short.poll", "This is short poll");
JSONObject json = build(data);
System.out.println(json.toString(4));
}
Ouptut:
{"activate": {
"message": {
"success": "success",
"short": {"poll": "This is short poll"},
"error": "error"
},
"title": "Good Title"
}}
Note : I used an exception to check for the existance of the key, if the map is huge, this could have some impact so you can simply use :
if(current.isNull(key)){
if (i == keys.length - 1) {
current.put(key, e.getValue());
} else {
JSONObject tmp = new JSONObject();
current.put(key, tmp);
current = tmp;
}
} else {
current = current.getJSONObject(key);
}
This was created using org.json/json
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 am getting this string from a service. I want a map or json out of this. It should look like this.
Map output
Total time taken:226006
nodea:10615
nodez:5308'
String timingTrace = "Total time taken:226006.,"
+ "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\"";
What I have tried so for is the below code. Can I do something better? Any library that can easily convert the above string to map.
if (timingTrace != null) {
arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,");
}
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":")
Map<String,Object> timestamps = new HashMap<String, Object>();
timestamp.put(totaltime[0], totaltime[1]);
String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:");
getMapped(nodetimestamp[1]);
public void getMapped(String json) throws JSONException, ParseException {
JSONObject obj = new JSONObject(json);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
String timetaken = JsonPath.read(json, "$." + key + ".timeTaken");
timestamp.put(key, timetaken);
}
}
You are using timestamp Map<> object in function getMapped(String json) that give you error because you haven't passed it you declare in function.
To get output you have mention change write below code instead of function getMapped(String json) :
JSONObject obj = new JSONObject(nodetimestamp[1]);
Iterator<String> keys = obj.keys();
while (keys.hasNext())
{
String key = keys.next();
String timetakenStr = obj.getString(key);
JSONObject child = new JSONObject(timetakenStr);
timestamps.put(key, child.getString("timeTaken"));
}
Using above code your Map<> will contain same what you mention.
OutPut :
{nodea=10615, Total time taken=226006, nodez=5308}
I am a newbie to JSON . So If this is a very basic doubt don't scold me . I have a JSON Object Reference and I want to get the Key(Object has only one Key Value Pair) . How do I get it in Java ?
You can use jsonObject.keys() for getting all keys. Then you may iterate over keys to get the first key out of them like :
Iterator<String> keys = jsonObject.keys();
if( keys.hasNext() ){
String key = (String)keys.next(); // First key in your json object
}
json.keys() will give all the keys in your JSONObject where json is an object of JSONObject
Recursively search for a key, and if found, return its value
String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
Iterator<?> keys = jObj.keys();
String key = "";
while (keys.hasNext() && !key.equalsIgnoreCase(findKey)) {
key = (String) keys.next();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
if (jObj.get(key) instanceof JSONObject) {
return recurseKeys((JSONObject)jObj.get(key), findKey);
}
}
return "";
}
Usage:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");