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?
Related
I have a very complex json structure. It contains many array elements and those array elements contains other array elements and so on..
Please see below json tree structure.
Json Tree Structure-1 :
Json Tree Structure-2 :
As highlighted above in yellow, I want to update the value of "rdKey" field.
I wrote below code and it is perfectly working fine :
String json = "escaped string (as it's a big string, I can't put it here)";
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("responseMap")) {
JSONObject responseMap = jsonObj.getJSONObject("responseMap");
if (responseMap.has("ValueJson")) {
JSONObject valueJson = responseMap.getJSONObject("ValueJson");
if (valueJson.has("ticketBean_CM")) {
JSONObject ticketBean_CM = valueJson.getJSONObject("ticketBean_CM");
if (ticketBean_CM.has("addByGamma")) {
String addByGamma = ticketBean_CM.getString("addByGamma");
System.out.println(addByGamma);
if (addByGamma.equals("VCE")) {
if (responseMap.has("ScreenJson")) {
JSONObject screenJson = responseMap.getJSONObject("ScreenJson");
if (screenJson.has("sections")) {
JSONArray sectionArray1 = screenJson.getJSONArray("sections");
if (sectionArray1.length() > 0) {
JSONObject section0 = sectionArray1.getJSONObject(0);
if (section0.has("sections")) {
JSONArray sectionArray2 = section0.getJSONArray("sections");
if (sectionArray2.length() > 3) {
JSONObject section6 = sectionArray2.getJSONObject(3);
if (section6.has("sections")) {
JSONArray sectionArray3 = section6.getJSONArray("sections");
if (sectionArray3.length() > 1) {
JSONObject section8 = sectionArray3.getJSONObject(1);
if (section8.has("elements")) {
JSONArray elementsArray1 = section8
.getJSONArray("elements");
if (elementsArray1.length() > 0) {
JSONObject elements1 = elementsArray1.getJSONObject(0);
if (elements1.has("elements")) {
JSONArray elementsArray2 = elements1
.getJSONArray("elements");
if (elementsArray2.length() > 4) {
JSONObject elements2 = elementsArray2
.getJSONObject(4);
if (elements2.has("rdKey")) {
System.out.println(
elements2.getString("rdKey"));
elements2.put("rdKey",
"CircuitID(FullPartial)");
System.out.println(
elements2.getString("rdKey"));
System.out.println(jsonObj.toString());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
I want you guys to help me if there is any better solution for this. Can I do it without traversing the entire json object (till I find the concerned field) ? This solution will not work if json tree structure gets changes, it needs to be static as a success scenario of this code.
Please suggest better solution.
If you want to escape traversing of JSON then you can use JSONPointer, available in same org.json library.
E.g.:
String query = <json_pointer_query to element array>
JSONPointer pointer = new JSONPointer(query);
JSONObject elementsArrayJSON = (JSONObject) pointer.queryFrom(jsonObj);
elementsArrayJSON.put("rdKey","CircuitID(FullPartial)");
JSON Pointer query language can be referred in:
https://www.rfc-editor.org/rfc/rfc6901
Note:
JSON Pointer is pretty basic, it doesn't support wild card. So you need to be sure about element names, otherwise it would throw exception.
If you're flexible on what library to use, maybe the JsonPath will be useful for you.
You can update all "elements" with "rdKey" using the following code:
JsonPath.parse(json).set("$..elements[?(#.rdKey)].rdKey", "CircuitID(FullPartial)").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 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");
I want to know if it is possible to check if some key exists in some jsonArray using java. For example: lets say that I have this json string:
{'abc':'hello','xyz':[{'name':'Moses'}]}
let's assume that this array is stored in jsnArray from Type JSONArray.
I want to check if 'abc' key exists in the jsnArray, if it exists I should get true else I should get false (in the case of 'abc' I should get true).
Thnkas
What you posted is a JSONObject, inside which there is a JSONArray. The only array you have in this example is the array 'xyz', that contains only one element.
A JSONArray example is the following one:
{
'jArray':
[
{'hello':'world'},
{'name':'Moses'},
...
{'thisIs':'theLast'}
]
}
You can test if a JSONArray called jArray, included inside a given JSONObject (a situation similar to the example above) contains the key 'hello' with the following function:
boolean containsKey(JSONObject myJsonObject, String key) {
boolean containsHelloKey = false;
try {
JSONArray arr = myJsonObject.getJSONArray("jArray");
for(int i=0; i<arr.length(); ++i) {
if(arr.getJSONObject(i).get(key) != null) {
containsHelloKey = true;
break;
}
}
} catch (JSONException e) {}
return containsHelloKey;
}
And calling that in this way:
containsKey(myJsonObject, "hello");
Using regular expressions will not work because of the opening and closing brackets.
You could use a JSON library (like google-gson) to transform your JSON Array into a java array and then handle it.
JSON arrays don't have key value pairs, JSON objects do.
If you store it as a json object you can check the keys using this method:
http://www.json.org/javadoc/org/json/JSONObject.html#has(java.lang.String)
If you use JSON Smart Library in Java to parse JSon String -
You can parse JSon Array with following code snippet -
like -
JSONObject resultsJSONObject = (JSONObject) JSONValue.parse(<<Fetched JSon String>>);
JSONArray dataJSon = (JSONArray) resultsJSONObject.get("data");
JSONObject[] updates = dataJSon.toArray(new JSONObject[dataJSon.size()]);
for (JSONObject update : updates) {
String message_id = (String) update.get("message_id");
Integer author_id = (Integer) update.get("author_id");
Integer createdTime = (Integer) update.get("created_time");
//Do your own processing...
//Here you can check null value or not..
}
You can have more information in - https://code.google.com/p/json-smart/
Hope this help you...
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;