How to fetch the distinct values from JSONObject in Android - java

I have the output in following JSONObject format. I want to fetch each and every value in this JSONObject. How can I do it? Need help! Thank you in advance.
{
"410": 19082,
"443": 19097,
"667": 19172
}

you can used below login for parsing key's value's of JSON
String json ="{\n" +
" \"410\": 19082,\n" +
" \"443\": 19097,\n" +
" \"667\": 19172\n" +
" }";
try {
JSONObject obj = new JSONObject(json);
for(int i = 0; i<obj.length(); i++){
Log.e("json parse", "Key = " + obj.names().getString(i) + " value = " + obj.get(obj.names().getString(i)));
}
}catch (Exception e)
{
e.printStackTrace();
}

Related

Dynamic update query for multiple columns using spring MVC

I am having a JSON data as shown below:
{
"table" : "customer",
"uniqueColumn" : "customer",
"uniqueColVal" : "cust_786",
"columns" :
[{
"column_1" : "column_1 Val",
"column_2" : "column_2 Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_n" : "column_n Val"
}]
}
I need a query to be executed and should be in the below form
UPDATE customer SET column_1 = 'column_1 Val', column_2 = 'column_2 Val', column_... = 'column_... Val', column_n = 'column_n Val' WHERE customer = 'cust_786';
I am using Spring MVC for processing this and the code I wrote is as follows. It is not complete.
#Override
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
Map<String, Object> response = new HashMap();
try
{
String table= data.get("table").toString();
String uniqueid = data.get("uniqueid").toString();
if (table!=null && uniqueid !=null)
{
String column = null, columnVal = null, updateColumn = null, updateColumnVal = null;
JSONObject jsonObj = new JSONObject(data);
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next().toString();
columnVal = json_Obj.getString(column).toString();
updateColumn = updateColumn + column.toString();
updateColumnVal = updateColumnVal + " = " + columnVal.toString() + "'";
}
}
System.out.println("UPDATE " + table+ " SET " + updateColumn +" = " + updateColumnVal + " WHERE " + data.get("uniqueColumn").toString() +" = '" + data.get("uniqueColVal").toString() +"';");
}
else
{
response.put("status", false);
LOGGER.info("Failed to get table>>> " + table+ " OR uniqueid >>> " + uniqueid);
}
}
catch (Exception e)
{
response.put("status", false);
LOGGER.error("Error #editLayerAttributeByUniqueID ", e);
System.err.println("Error #editLayerAttributeByUniqueID " + e);
}
return response;
}
It would be very much helpful if someone could help me out here. Thanks in advance.
I could find a satisfying answer at the end. Please follow the below instructions.
You need to import some packages and I am mentioning the Maven repository for the same below. Add the dependency in your pom.xml
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<!-- For PostgreSQL Database connectivity -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
Now Import the packages in your Impl file as follows:
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
The logic is explained in the below code
public JdbcTemplate getJdbcTemplate()
{
return jdbcTemplate;
}
#Override
//Defines a Map named as updateTabColumnValues to get data from client
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
//Defines a Map named as response to send data to client
Map<String, Object> response = new HashMap();
try
{
String table = data.get("table").toString();
String uniqueColumn = data.get("uniqueColumn").toString();
String uniqueValue = data.get("uniqueValue").toString();
if ((uniqueColumn != null && uniqueValue != null) && table != null)
{
String column;
String columnVal;
String keyValuePair = "";
String query = null;
JSONObject jsonObj = new JSONObject(data);
//Gets values in the key columns to columnsToUpdate
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
//Loops each elements with in the array
if (columnsToUpdate.length() > 0)
{
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
//Create Key Value pair without adding comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "'";
}
else
{
//Create Key Value pair with comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "' , ";
}
}
int queryValidator = -1;
query = "UPDATE " + table +" SET "+ keyValuePair + " WHERE " + uniqueColumn + " = '" + uniqueValue +"';";
LOGGER.info("Query is >>> " + query);
//Uses getJdbcTemplate() to run query
queryValidator = getJdbcTemplate().update(query);
//Validating the query execution status with database
if (queryValidator >= 0)
{
response.put(stateOfstatus,true);
}
else
{
response.put(stateOfstatus,false);
}
}
else
{
response.put(stateOfstatus, false);
}
}
else
{
response.put(stateOfstatus, false);
LOGGER.info("Failed to get table >>> " + table + " OR uniqueColumn >>> " + uniqueColumn + " OR uniqueValue >>>" + uniqueValue);
}
}
catch (Exception e)
{
response.put(stateOfstatus, false);
LOGGER.error("Error in updateTabColumnValues ", e);
response.put("message", e);
}
return response;
}
This was an RnD related task taken under a special usecase. The above logic perfectly and effectivelty delivers the output.

Parse JSON multiple objects

I am trying to parse the below json but unable to do that as stack over flow error comes in.
Here is the JSON -
[{
"Class": "1",
"school": "test",
"description": "test",
"student": [
"Student1",
"Student2"
],
"qualify": true,
"annualFee": 3.00
}]
Here is the code which is failing currently.
String res = cspResponse.prettyPrint();
org.json.JSONObject obj = new org.json.JSONObject(res);
org.json.JSONArray arr = obj.getJSONArray(arrayName);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
dataStatus = arr.getJSONObject(i).getString(key);
System.out.println("dataStatus is \t" + dataStatus);
}
Usecases are:
To get the value key "class"
Get the value from Student
Get the value from school
I appreciate your help.
update-1
Code more info on stack trace updated with below details.
cls = 1
error- org.json.JSONException: JSONObject["student "] not a string.
Stack trace-
public String getString(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
When I ran the code with the below answers, here its failing for student is not a string.
The answers I used from first two comments and both have the same error. I appropriate your help.
Your json fragment is invalid - the last comma breaks the parsing. But the rest of the code is quite workable.
String res = "[\n" +
" {\n" +
" \"Class\": \"1\",\n" +
" \"school\": \"test\",\n" +
" \"description\": \"test\",\n" +
" \"student\": [\n" +
" \"Student1\",\n" +
" \"Student2\"\n" +
" ],\n" +
" \"qualify\": true,\n" +
" \"annualFee\": 3.00\n" +
" }\n" +
"]";
JSONArray arr = new JSONArray(res);
for (int i = 0; i < arr.length(); i++) {
JSONObject block = arr.getJSONObject(i);
Integer cls = block.getInt("Class");
System.out.println("cls = " + cls);
Object school = block.getString("school");
System.out.println("school = " + school);
JSONArray students = block.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
should output
cls = 1
school = test
student[0] = Student1
student[1] = Student2
Your JSON reponse root is array but you consider your JSON response as JSON object
Changing your parsing json code as below
String res=cspResponse.prettyPrint();
org.json.JSONArray arr = new org.json.JSONArray(res);
String dataStatus=null;
for (int i = 0; i < arr.length(); i++) {
org.json.JSONObject obj=arr.getJSONObject(i);
dataStatus = obj.getString(key);
System.out.println("dataStatus is \t" + dataStatus);
String schoolName = org.getString("school");
System.out.println("school => " + schoolName);
org.json.JSONArray students = obj.getJSONArray("student");
System.out.println("student[0] = " + students.get(0));
System.out.println("student[1] = " + students.get(1));
}
You can use simple JSONObject class and Simple JSONParser for parsing the JSON.
1. Parse the JSON.
org.json.simple.JSONParser parser = new org.json.simple.JSONParser();
org.json.simple.JSONObject parsedJSON = parser.parse(inputJSON);
2. To get class:
String class = parsedJSON.get("Class");
3. To get Students:
org.json.simple.JSONArray studentArray = parsedJSON.get("student");
4. To Get School:
String school = parsedJSON.get("school");
After the above steps, you can run a for-loop to print the class and students.

Parsing JSON - null of type JSONObject cannot be converted to JSONArray

I'm trying to take the JSON from BITTREX and parse it and present it to the screen in Android Studio. This works for me with test JSON I made myself plus other requests i have made using the same API. However, when i go to use the actual request I need i get the following error :
JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is the request used: https://bittrex.com/api/v1.1/public/getmarketsummaries
API Documentation
Here is the Code :
public class fetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
JSONArray myJsonArray = new JSONArray(data); //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("Timestamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
MainActivity.data.setText(this.dataParsed);
}
}
Any thoughts would be greatly appreciated. Thanks :)
**UPDATE - SOLVED **
I added the following line before the loop and it solved the issue.
//target the "result" Array of objects(BTC,LTC,ETH) and map them to a JsonArray for parsing
JSONArray myJsonArray = myJsonObj.getJSONArray("result");
The exception is perfectly valid. Your trying to convert json object into json array. Try below code
remove "\n" character at the end.
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries\n")
add below logs
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
}
Log.debug("api_response","api-response->"+data);
and try below code
if(data!= null){ // add this if condition too.
JSONObject jsonObj = new JSONObject(data);
JSONArray myJsonArray = jsonObj.getJSONArray("result"); ; //store json in a json array
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
The json data returned by the API is in the following format:
{
"success": true,
"message": "",
"result": [
{
},
{
}
]
}
So you need to get the whole data as JSONObject first, then from it you can extract the JSONArray with the "result" key.
The code is something like this:
// get the JSONObject from the data
JSONObject jsonObject = new JSONObject(data);
// then you get the array with result key
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
// now you can process the item here.
}
UPDATE
The above code is working. The remaining problem is there is a typo in your key. You're using "Timestamp" but the existing key is "TimeStamp". Here is the working code:
public class FetchData extends AsyncTask<Void,Void,Void> {
String data=""; //all json lines after loop
String dataParsed ="";
String singleParsed =""; //parsed attributes
#Override
protected Void doInBackground(Void... voids) {
//Background Thread i.e API request
try {
URL url = new URL("https://bittrex.com/api/v1.1/public/getmarketsummaries");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream(); //read data in from the connection
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //Buff reader to read the inputstream (otherwise we get ints)
String line ="";
//Loop that reads all lines and represents them to as a string
while(line != null) {
line = bufferedReader.readLine(); //read line of json and assign to "line" if not null
data = data + line;
Log.d("DATA", "line = " + line);
}
Log.d("DATA", "construct data = " + data);
JSONObject jsonObject = new JSONObject(data);
JSONArray myJsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < myJsonArray.length(); i++) {
//Itterate through the array and get each object i.e btc,ltc
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
//Single JSON object parsed
singleParsed = "Coin" + myJsonObject.get("MarketName") + "\n" +
"high" + myJsonObject.get("High") + "\n" +
"low" + myJsonObject.get("Low") + "\n" +
"volume" + myJsonObject.get("Volume") + "\n" +
"last" + myJsonObject.get("Last") + "\n" +
"basevolume" + myJsonObject.get("BaseVolume") + "\n" +
"time" + myJsonObject.get("TimeStamp") + "\n" +
"bid" + myJsonObject.get("Bid") + "\n" +
"ask" + myJsonObject.get("Ask") + "\n" +
"openbuyorders" + myJsonObject.get("OpenBuyOrders") + "\n" +
"opensellorders" + myJsonObject.get("OpenSellOrders") + "\n" +
"prevday" + myJsonObject.get("PrevDay") + "\n" +
"created" + myJsonObject.get("Created") + "\n";
dataParsed = dataParsed + singleParsed + "\n";
}
}catch(MalformedURLException e ){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//UI thread
//MainActivity.data.setText(this.dataParsed);
Log.d("DATA", "data = " + this.dataParsed);
}
}

Android JSONObject need print null

data from:
{"i":"One","o":"two","u":"","a":"four"}
code:
JSONObject data;
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(data.optString("o") + " " +
data.optString("u")+ " " + data.optString("a"));
}
print:
i=one
o=two
u=
a=four
I need print:
i=one
o=two
u=null
a=four
how to do?Thank you read my question ,please help me
As Sotirios Delimanolis said, you can check if that is a empty string, return "null" text.
for (int i = 0; i < list.length(); i++) {
data = list.optJSONObject(i);
mSearchList.add(
data.optString("o").equals("") ? "null" : data.optString("o") + " " +
data.optString("u").equals("") ? "null" : data.optString("u") + " " +
data.optString("a").equals("") ? "null" : data.optString("a"));
}
Use this method
getValidString(JSONObject json,String key){
String value="";
try{
value=json.getString(key);
}catch(Exception e){
e.printStackTrace();
}
if(value.length==0){
value="null";
}
}

Parsing a flat JSON array with no indice

I am scratching my head to figure out how to parse the following JSON object.
[
{
"result": true,
"response": "Successfully got list of users in radius of 10km"
},
{
"username": "elize",
"photo": "http://www.embedonix.com/apps/mhealth/images/elize/elize.png"
},
{
"username": "mario",
"photo": "http://www.embedonix.com/apps/mhealth/images/mario/mario.png"
}
]
This is I guess a single index json array. The first part tells that the operation of building the json object was ok.
Then there are pairs of username and photo which I have to parse them and put them in a list:
public class User {
private String mName;
private String mPhotoURl;
public User(String name, String url)
{
///
}
}
So if the first entry of json is result -> true I should have a ArrayList<User>.
I tried to do the following but it always raises the JSONParse exception:
try {
JSONObject json = new JSONObject(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONArray obj = json.getJSONArray(String.valueOf(i));
Log.i(TAG, i + " username: " + obj.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Just try this way
try {
JSONArray jsonArray = new JSONArray(data);
int length = jsonArray.length();
for (int i = 1; i < length; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
if(i==0){
Log.i(TAG, i + " result: " + obj.getString("result"));
Log.i(TAG, i + " response: " + obj.getString("response"));
}else{
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try Code...something like this..
try {
JSONArray json = new JSONArray(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONObject childObject = json.getJSONObject(i);
if(i==0){
String result = child.getBoolean("result");
String resp = child.getString("response");
} else {
String username = child.getString("username");
String photo = child.getString("photo");
Log.i(TAG, i + " username: " + username);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories