Verifying if Key Values of Redis(Jedis) are JSON - java

I'm trying to make a Java program that iterate over Redis database, veryfing the key values; if it's a valid JSON, extract into a separate schema(nothing done about this yet); else, do nothing, but keep searching over the other keys.
Here's my function code:
Jedis jedis = new Jedis("localhost");
ScanResult<String> scanResult = jedis.scan("0");
List<String> keys = scanResult.getResult();
String nextCursor = scanResult.getStringCursor();
JSONParser parser = new JSONParser();
int counter = 0;
while(true) {
if(nextCursor.equals("0")) {
break;
}
scanResult = jedis.scan(nextCursor);
nextCursor = scanResult.getStringCursor();
keys = scanResult.getResult();
for(counter = 0; counter <= keys.size(); counter++) {
try {
JSONObject json = (JSONObject) parser.parse(keys.get(counter).toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
System.out.println(keys = scanResult.getResult());
}
jedis.close();
I'm getting trouble with JSON Parse (idk if I'm using him correctly) because I think I'm only getting the KEY NAMES (not their values).
I tried to use Map<String, String> = scanResult.getResult() instead of List<String>, but it point out a Typemismatch problem.
Seems like easy to solve, but I'm kinda stuck at this point... Any tip that could help will be welcome, thanks.
P.S.: I cannot use modules like ReJSON, must be with native redis functions.

I think I got it. Answering my own question:
public void readRedis() {
Jedis jedis = new Jedis("localhost");
ScanResult<String> scanResult = jedis.scan("0");
String nextCursor = scanResult.getStringCursor();
JSONParser parser = new JSONParser();
int counter = 0;
while (true) {
nextCursor = scanResult.getStringCursor();
List<String> keys = scanResult.getResult();
for (counter = 0; counter < keys.size(); counter++) {
if(counter == keys.size()) {
break;
}
try {
JSONObject json = (JSONObject) parser.parse(jedis.rpop(keys.get(counter)));
documentoJson(json);
System.out.println("Added to function 'documentoJson'");
} catch (ParseException e) {
System.out.println("Not a valid JSON");
}
}
if (nextCursor.equals("0")) {
break;
}
scanResult = jedis.scan(nextCursor);
}
jedis.close();
}
public JSONArray documentoJson(JSONObject json) {
JSONObject jObject = new JSONObject();
JSONArray jArray = new JSONArray();
jArray.add(json);
jObject.put("JSON Document", jArray);
return jArray;
}

Related

Recieve JSON Object with 2 Arrays

im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.
public static String constructJSON(Integer[] array, String[] array2) {
JSONObject mainObj = new JSONObject();
try {
JSONObject firstArray = new JSONObject();
firstArray.put("array0", array[0]);
firstArray.put("array1", array[1]);
firstArray.put("array2", array[2]);
firstArray.put("array3", array[3]);
firstArray.put("array4", array[4]);
JSONObject secondArray = new JSONObject();
secondArray.put("sArray0", array2[0]);
secondArray.put("sArray1", array2[1]);
secondArray.put("sArray2", array2[2]);
secondArray.put("sArray3", array2[3]);
secondArray.put("sArray4", array2[4]);
JSONArray JArr = new JSONArray();
JArr.put(firstArray);
JArr.put(secondArray);
mainObj.put("arrays", JArr);
} catch (JSONException e) {
}
return mainObj.toString();
}
And now the method in Android Studio:
private void getBW(String krankheit) {
RequestParams params = new RequestParams();
params.put("krankheit", krankheit);
// Invoke RESTful Web Service with Http parameters
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
// JSON Object
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("array1");
JSONArray secondJsonArr= obj.getJSONArray("array2");
for (int k = 0; k < 5; k++) {
Bewertung1[k] = (Integer) firstJsonArr.get(k);
}
for (int j = 0; j < 5; j++) {
medikament[j] = (String) secondJsonArr.get(j);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
I tried different solution´s, but none of them worked for me. I hope you guys can help me.
I would recommend you to use gson library for android. Its provides simple function to parse from and to json object.
Have a look at this library : https://github.com/google/gson
You switched your function istead of what you wanted it does [{}{}]
Try this:
public static String constructJSON(Integer[] array, String[] array2) {
try {
JSONArray firstArray = new JSONArray ();
firstArray.put( array[0]);
firstArray.put( array[1]);
firstArray.put( array[2]);
firstArray.put( array[3]);
firstArray.put( array[4]);
JSONArray secondArray = new JSONArray ();
secondArray.put(array2[0]);
secondArray.put( array2[1]);
secondArray.put( array2[2]);
secondArray.put( array2[3]);
secondArray.put( array2[4]);
JSONObject JArr = new JSONObject();
JArr.put("firstArr",firstArray);
JArr.put("secondArr", secondArray);
return JArr.toString();
} catch (JSONException e) {
}
return null;
}
this will give you the JSon you wanted , and this is the main code to use it:
JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
this is good for practices but later you should use a library that does these type of things for you like Gson etc...

Parsing another JSON Format

So here's the following code :
jObj = new JSONObject(valeurARenvoyer);
hauteur = jObj.getString("niveauEau");
debit = jObj.getString("debit");
date = jObj.getString("dateReleve");
batterie = jObj.getString("chargeBatterie");
presence = jObj.getString("etatPerimetrique");
bat = jObj.getString("chargeBatterie");
So i used this code to parse a JSON which was like that :
{"id":"15","id_Station":"Artiguelouve","Date_Releve":"2017-02-16 16:07:41","Niveau_Eau":"29","Charge_Batterie":"9","Etat_Perimetrique":"0","Debit":"13.35"}
It worked well, but now my JSON response looks like that :
{"Station":"Artiguelouve","debit":[{"niveauEau":0,"debit":32.5,"dateReleve":{"date":"2017-06-08 15:59:03","timezone_type":3,"timezone":"Europe\/Paris"},"idStation":"Artiguelouve","etatPerimetrique":true,"chargeBatterie":14590}]}
With this response i can't find how to parse this.
valeurARenvoyer is my JSON. Can you have any solution to do that please ?
add this code to get response
JSONObject jsonObject = new JSONObject(jsonResponse);//put your json response
JSONArray jsonArray = null;
try {
String station = jsonObject.getString("Station");
jsonArray = jsonObject.getJSONArray("debit");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
int niveauEau = jsonObject1.getInt("niveauEau");
int debit = jsonObject1.getInt("debit");
String isStation = jsonObject1.getString("idStation");
boolean etatPerimetrique = jsonObject1.getBoolean("etatPerimetrique");
int chargeBatterie = jsonObject1.getInt("chargeBatterie");
JSONObject jsonObject2 = jsonObject1.getJSONObject("dateReleve");
String date = jsonObject2.getString("date");
int timezone_type = jsonObject2.getInt("timezone_type");
String timezone = jsonObject2.getString("timezone");
}
} catch (JSONException e) {
e.printStackTrace();
}
try this code
try {
JSONObject jsonObject = new JSONObject(valeurARenvoyer);
JSONArray jsonArray = jsonObject.getJSONArray("debit");
for(int i = 0; i < jsonArray.length(); i++){
// you can get niveauEau, debit, idStation, etatPerimetrique,
// chargeBatterie, dateReleve JsonObject values in this loop
}
} catch (JSONException e) {
e.printStackTrace();
}

Parse JSONArray present in generic ArrayList

I have some issue with JSONArray, As I am having a JSON data present in generic ArrayList but I don't have any idea that how to parse that json data and display in list, I am using org.json library
Below is my json data which is present in array list:
[{"story":"Gaurav Takte shared a link.","created_time":"2017-02-14T19:08:34+0000","id":"1323317604429735_1307213186040177"},{"story":"Gaurav Takte shared a link.","created_time":"2017-02-02T14:22:50+0000","id":"1323317604429735_1295671703860992"},{"message":"Hurray....... INDIA WON KABBADI WORLD CUP 2016","created_time":"2016-10-22T15:55:04+0000","id":"1323317604429735_1182204335207730"},{"story":"Gaurav Takte updated his profile picture.","created_time":"2016-10-21T05:35:21+0000","id":"1323317604429735_1180682575359906"},{"message":"Friends like all of you \u2026 I would love to keep forever.\n#oldmemories with # besties \n#happydays","story":"Gaurav Takte with Avi Bhalerao and 5 others.","created_time":"2016-10-21T05:33:55+0000","id":"1323317604429735_1180682248693272"},{"message":"\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.\nतुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना\nसुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच\nबाप्पाच्या चरणी प्रार्थना. \"\nगणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!","story":"Gaurav Takte with Avi Bhalerao and 18 others.","created_time":"2016-09-05T05:06:58+0000","id":"1323317604429735_1133207030107461"}]
And here is my code:
ArrayList data_arr1= (ArrayList) ((Map) parsed.get("posts")).get("data"); JSONArray array = new JSONArray(data_arr1); for(int i = 0; i < array.length(); i++){ try { JSONObject obj = array.getJSONObject(i); Log.p(obj.toString()); } catch (JSONException ex) { ex.printStackTrace(); } }
So how can i parse this json using org.json library.
Here is the best solution of in-proper json response.
You can try this code I hope it works good..
String result = "Your JsonArray Data Like [{}]";
ArrayList<String> arrayList = new ArrayList<>();
try {
JSONArray jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String story = null;
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String ct = jsonobject.getString("created_time");
String id = jsonobject.getString("id");
if (msg == null){
msg = "";
}
if (story == null){
story = "";
}
arrayList.add(story + msg + ct + id);
// Smodel is getter model
// arrayList.add(new Smodel(story, msg, ct, id));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Android, cannot iterate through JSONArray inside for-loop

I'm trying the following to iterate through each JSONObject in an JSONArray but it's not working. I check the length of the JSONArray in the Log and it gives me the correct lenght, but I can't get the JSONObject at each element of the JSONArray. Also, each element should be a JSONObject with 8 key/value pairs. Any feedback is greatly appreciated, thanks.
if (getMyJSONArray() != null) {
newJSONArray = getMyJSONArray();
try {
// Did this because the JSONArray was inside a JSONArray
innerJSONArray = newJSONArray.getJSONArray(0);
} catch (JSONException e) {
e.printStackTrace();
}
if (innerJSONArray != null) {
// This gives me the right length
Log.i("innerJSONArray.length: ", String.valueOf(innerJSONArray.length()));
for (int i = 0; innerJSONArray.length() < 0; i++) {
try {
// This doesn't work
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);
// This doesn't work either
JSONObject jsonObject2 = new JSONObject(innerJSONArray.getString(i));
…(more code below to use if the part above works)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In your for loop innerJSONArray.length() < 0; should be i < innerJSONArray.length().
Then this line should work as expected:
JSONObject jsonObject1 = innerJSONArray.getJSONObject(i);

JsonArray to List in Java

I have a problem with parsing JsonArray response.
I take JsonObject from JsonArray, parse it and set in entity message and then that message add to ArrayList.
Problem is that in ArrayList that I want to return I always have only one message. This must be some fundamental error but I cant find it.
public ArrayList<Message> getSearchInfo(String response) {
ArrayList<Message> searchResult = new ArrayList<Message>();
int jsonMessageId = -1;
String jsonDate = "";
String jsonText = "";
String jsonAutor = "";
String jsonSource = "";
int jsonThemeID = -1;
int jsonSourceID = -1;
try {
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
Message m = new Message();
// Pulling items from the array
jsonMessageId = oneObject.getInt("MessageId");
jsonDate = oneObject.getString("CreatedDate");
jsonText = oneObject.getString("TextMessage");
jsonAutor = oneObject.getString("Autor");
jsonSource = oneObject.getString("Source");
jsonThemeID = oneObject.getInt("ThemeId");
jsonSourceID = oneObject.getInt("SourceId");
m.setMessageId(jsonMessageId);
m.setMessageText(jsonText);
m.setDate(jsonDate);
m.setAutor(jsonAutor);
m.setSource(jsonSource);
m.setThemeId(jsonThemeID);
m.setSourceId(jsonSourceID);
searchResult.add(m);
} catch (JSONException e) {
Log.d("URL EXC", "Exception 2");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return searchResult;
}
p.s. I use web-api as service and via android I take resources from service.
Any idea where is my mistake here?
You redefine your list every time in the loop.
Change your code from
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
searchResult = new ArrayList<Message>();
To
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
searchResult = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
try {

Categories

Resources