Problem in code while parsing Json string in Java - java

I'm new to Java and i was using python and coding is different for me. I'm trying to make a string count with java , I have a problem when I execute it doesn't update the values of my json file it creates another textual in the subdirectory here is my code:
package sender;
import java.util.Iterator;
import java.util.Scanner; // import the Scanner class
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class contar {
public static void main(String[] args) throws ParseException, IOException {
Scanner myObj = new Scanner(System.in);
String userName;
char[] cadena;
char caracter;
// Enter username and press Enter
System.out.println("Enter username");
userName = myObj.nextLine();
cadena = userName.toCharArray();
boolean[] yaEstaElCaracter = new boolean[Character.MAX_VALUE];
int[] cuantasVeces = new int[Character.MAX_VALUE];
for(int i =0;i<cadena.length;i++){
caracter = cadena[i];
System.out.println(caracter);
if(cadena[i]==caracter){
cuantasVeces[caracter]++;
}
yaEstaElCaracter[caracter] = true;
}//Fin Para
//Crea el json
Object a;
Object b;
JSONObject jsd = new JSONObject();
jsd.put("listado","2");
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject();
for(int i = 0; i < yaEstaElCaracter.length; i++){
if(yaEstaElCaracter[i]) {
a= (char) i;
b = cuantasVeces[i];
//JSONObject jsd = new JSONObject();
/*jsd.put("listado","2");
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject();*/
obj.put((char) i,cuantasVeces[i] );
System.out.println((char) i +" "+cuantasVeces[i]+" veces.");
}
}
list.add(obj);
jsd.put("frecuencias", list);
File l = new File("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea");
String[] bus = l.list();
if (bus == null || bus.length == 0) {
System.out.println("No hay elementos dentro de la carpeta actual");
try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
file.write(jsd.toString());
file.flush();
file.close();
}catch(Exception e) {}
}else {
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json"))
{
Object abc = jsonParser.parse(reader);
JSONObject letras = (JSONObject) abc;
JSONArray lang = (JSONArray) letras.get("frecuencias");
for (int k = 0; k < lang.size(); k++) {
System.out.println("The " + k + " element of the array: " + lang.get(k));
}
Iterator k = lang.iterator();
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
JSONArray
}
}
while (k.hasNext()) {
JSONObject innerObj = (JSONObject) k.next();
for (int i = 0; i < innerObj.size(); i++) {
System.out.println(i);
}
//System.out.println(innerObj.get(cadena.toString()));
}
//Iterate over employee array
//employeeList.forEach( emp -> parseEmployeeObject( (JSONObject) emp ) );
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
This is my output:
{"listado":"2","frecuencias":[{" ":6,"a":4,"c":2,"d":2,"e":3,"g":1,"i":4,"m":3,"o":5,"p":1,"q":1,"r":2,"s":1,"t":1,"u":1,"y":1}]}{"a":6,c":2,"d":2,"e":3,} <---- I don't need this just update it

First you need to fix this catch(Exception e) {}. If you hide or don't do anything with an exception then you will have no idea what has broken and why. Also, you only ever write to the file if bus == null or if bus.length == 0, is that correct? And then you only ever write your file to "C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json" is that path correct?
Edit your code to include some debugging and to show the error message:
if (bus == null || bus.length == 0) {
System.out.println("No hay elementos dentro de la carpeta actual");
try (FileWriter file = new FileWriter("C:\\Users\\andre\\Documents\\9SEMENESTRE\\FATIGA\\tarea\\Reporte.json")){
//Print a message to check if your code ever for here
System.out.println("Attempting to write the file");
file.write(jsd.toString());
file.flush();
//Print a success message
System.out.println("The file was successfully written to");
}
catch(Exception e) {
//Print the error to the console
e.printStackTrace();
}
}
Now you will be able to see if your code even got as far as writing to the file, and why it failed.
If you are still stuck then you need to update your question to include more information, including debugging details.

First, what is contents in JSONObject jsonObject = new JSONObject(contents.trim());? I'm pretty sure you're referencing a variable above that you changed the name of at some point, because I don't see it anywhere else in this code.
Iterator k = lang.iterator();
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
JSONArray
}
}
while (k.hasNext()) {
JSONObject innerObj = (JSONObject) k.next();
for (int i = 0; i < innerObj.size(); i++) {
System.out.println(i);
}
//System.out.println(innerObj.get(cadena.toString()));
}
Somewhere in here you're missing a call to jsd.
I haven't run the script, but just reading it over, what I see is that you check to see if the file you are looking for exists, and if it doesn't you create the file using the data you have parsed into the object jsd. But if it does exists, you never do that. You seem to correctly open the file, read it into the buffer, and then ... you read that file back into the same file? Actually, you don't seem to do anything with it.
So I think that's where your issue is.
Two things to help:
Like sorifiend alludes to, use your catchs better. Put some sort of println or message for each one that lets you know where the error occured, what type it is, and then, yeah print the stack trace.
I suggest you go through and write comments about what need to get done, and about each step that's being completed. Lean towards the side of being overly explicit. Even write a comment for each line. This way, when you are looking through your code, you'll notice when you aren't doing something important (like writing to the file).

Related

Verifying if Key Values of Redis(Jedis) are JSON

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;
}

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();
}

Java JSON converter "undefined for type" error

Using Eclipse, I’m converting data to JSON. I’ve downloaded the json.jar file and added it to my class path. I’ve imported these,
import org.json.JSONArray;
import org.json.JSONObject;
But when I try to use .add, .toJSONString and .contains I get errors like these,
The method add(String) is undefined for the type JSONArray
The method add(JSONObject) is undefined for the type JSONArray
The method toJSONString() is undefined for the type JSONObject
Why is this happening? Here is the full code below.
private JSONObject getJson(){
JSONObject obj = new JSONObject();
String forename = null;
String surname = null;
JSONArray nodes = new JSONArray();
JSONArray links = new JSONArray();
Map<Integer,Integer> sourceMap = new HashMap<Integer, Integer>();
Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>();
int linkSourceActivity = -1;
int linkTargetActivity = -1;
String activity =null;
int sourceId = -1;
int targetId = -1;
int nodeIndex = 0;
int targetIndex = -1;
JSONObject jsonLine = null;
// Iterate over the Map of links
for(Integer index : this.links.keySet()){
// gather information needed for Json object
Link link = this.links.get(index);
// nodes need
sourceId = link.getSourceId();
targetId = link.getTargetId();
forename = people.getValue(link.getSourceId()).getForenames();
surname = people.getValue(link.getSourceId()).getSurname();
linkSourceActivity = link.getSourceActivityCode();
//If source node doesn't exist, create it
if(!sourceMap.containsKey(sourceId)){
// Create a node and add to array
jsonLine = new JSONObject();
jsonLine.put("name",forename+ " " +surname);
jsonLine.put("group", linkSourceActivity);
jsonLine.put("role", "Director");
nodes.add(jsonLine);
// add entry to map
sourceMap.put(sourceId, nodeIndex);
nodeIndex++;
}
forename = people.getValue(link.getTargetId()).getForenames();
surname = people.getValue(link.getTargetId()).getSurname();
linkTargetActivity = link.getTargetActivityCode();
activity = link.getTargetActivity();
targetIndex = (targetId * 0x1f1f1f1f) ^ linkTargetActivity;
// If the target node doesn't exist, create it
if(!targetMap.containsKey(targetIndex)){
jsonLine = new JSONObject();
jsonLine.put("name", forename+ " " +surname);
jsonLine.put("group", linkTargetActivity);
jsonLine.put("role", activity);
nodes.add(jsonLine);
// add entry to map
targetMap.put(targetIndex, nodeIndex);
nodeIndex++;
}
// links need
// source (position in node array)
// target (position in node array)
int sourcePos = sourceMap.get(sourceId);
int targetPos = targetMap.get(targetIndex);
int value = link.getMultiplicity();
// Build the array of play titles for this Link
List<Integer> productionIds = link.getProductions();
JSONArray playTitles = new JSONArray();
int playId = -1;
String playName = null;
for (Integer Id : productionIds){
playId = productions.getValue(Id).getPlayId();
playName = plays.getValue(playId).getMainTitle();
// don't include duplicate titles
if(!playTitles.contains(playName)){
playTitles.add(plays.getValue(playId).getMainTitle());
}
}
JSONObject linkLine = new JSONObject();
linkLine.put("source", sourcePos);
linkLine.put("target", targetPos);
linkLine.put("value", value);
linkLine.put("plays", playTitles);
links.add(linkLine);
} // end iterate over Links
obj.put("nodes", nodes);
obj.put("links", links);
return obj;
} // end getJson method
// Method to write Json to a file
public void writeJson(String path){
try {
FileWriter file = new FileWriter(path);
file.write(jsonLinks.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end JsonOutput
Yes, org.json.JSONArray does not have a method put(..). See the JavaDoc.
You could use public JSONArray put(java.lang.Object value).
Was using the wrong library, code works fine with JSONsimple ! :)

Creating hashmap from json data

I am working on a very simple application for a website, just a basic desktop application.
So I've figured out how to grab all of the JSON Data I need, and if possible, I am trying to avoid the use of external libraries to parse the JSON.
Here is what I am doing right now:
package me.thegreengamerhd.TTVPortable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import me.thegreengamerhd.TTVPortable.Utils.Messenger;
public class Channel
{
URL url;
String data;
String[] dataArray;
String name;
boolean online;
int viewers;
int followers;
public Channel(String name)
{
this.name = name;
}
public void update() throws IOException
{
// grab all of the JSON data from selected channel, if channel exists
try
{
url = new URL("https://api.twitch.tv/kraken/channels/" + name);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
data = new String(in.readLine());
in.close();
// clean up data a little, into an array
dataArray = data.split(",");
}
// channel does not exist, throw exception and close client
catch (Exception e)
{
Messenger.sendErrorMessage("The channel you have specified is invalid or corrupted.", true);
e.printStackTrace();
return;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dataArray.length; i++)
{
sb.append(dataArray[i] + "\n");
}
System.out.println(sb.toString());
}
}
So here is what is printed when I enter an example channel (which grabs data correctly)
{"updated_at":"2013-05-24T11:00:26Z"
"created_at":"2011-06-28T07:50:25Z"
"status":"HD [XBOX] Call of Duty Black Ops 2 OPEN LOBBY"
"url":"http://www.twitch.tv/zetaspartan21"
"_id":23170407
"game":"Call of Duty: Black Ops II"
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-profile_image-121d2cb317e8a91c-300x300.jpeg"
"banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_header_image-7c894f59f77ae0c1-640x125.png"
"_links":{"subscriptions":"https://api.twitch.tv/kraken/channels/zetaspartan21/subscriptions"
"editors":"https://api.twitch.tv/kraken/channels/zetaspartan21/editors"
"commercial":"https://api.twitch.tv/kraken/channels/zetaspartan21/commercial"
"teams":"https://api.twitch.tv/kraken/channels/zetaspartan21/teams"
"features":"https://api.twitch.tv/kraken/channels/zetaspartan21/features"
"videos":"https://api.twitch.tv/kraken/channels/zetaspartan21/videos"
"self":"https://api.twitch.tv/kraken/channels/zetaspartan21"
"follows":"https://api.twitch.tv/kraken/channels/zetaspartan21/follows"
"chat":"https://api.twitch.tv/kraken/chat/zetaspartan21"
"stream_key":"https://api.twitch.tv/kraken/channels/zetaspartan21/stream_key"}
"name":"zetaspartan21"
"delay":0
"display_name":"ZetaSpartan21"
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_offline_image-b20322d22543539a-640x360.jpeg"
"background":"http://static-cdn.jtvnw.net/jtv_user_pictures/zetaspartan21-channel_background_image-587bde3d4f90b293.jpeg"
"mature":true}
Initializing User Interface - JOIN
All of this is correct. Now what I want to do, is to be able to grab, for example the 'mature' tag, and it's value. So when I grab it, it would be like as simple as:
// pseudo code
if(mature /*this is a boolean */ == true){ // do stuff}
So if you don't understand, I need to split away the quotes and semicolon between the values to retrieve a Key, Value.
It's doable with the following code :
public static Map<String, Object> parseJSON (String data) throws ParseException {
if (data==null)
return null;
final Map<String, Object> ret = new HashMap<String, Object>();
data = data.trim();
if (!data.startsWith("{") || !data.endsWith("}"))
throw new ParseException("Missing '{' or '}'.", 0);
data = data.substring(1, data.length()-1);
final String [] lines = data.split("[\r\n]");
for (int i=0; i<lines.length; i++) {
String line = lines[i];
if (line.isEmpty())
continue;
line = line.trim();
if (line.indexOf(":")<0)
throw new ParseException("Missing ':'.", 0);
String key = line.substring(0, line.indexOf(":"));
String value = line.substring(line.indexOf(":")+1);
if (key.startsWith("\"") && key.endsWith("\"") && key.length()>2)
key = key.substring(1, key.length()-1);
if (value.startsWith("{"))
while (i+1<line.length() && !value.endsWith("}"))
value = value + "\n" + lines[++i].trim();
if (value.startsWith("\"") && value.endsWith("\"") && value.length()>2)
value = value.substring(1, value.length()-1);
Object mapValue = value;
if (value.startsWith("{") && value.endsWith("}"))
mapValue = parseJSON(value);
else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))
mapValue = new Boolean (value);
else {
try {
mapValue = Integer.parseInt(value);
} catch (NumberFormatException nfe) {
try {
mapValue = Long.parseLong(value);
} catch (NumberFormatException nfe2) {}
}
}
ret.put(key, mapValue);
}
return ret;
}
You can call it like that :
try {
Map<String, Object> ret = parseJSON(sb.toString());
if(((Boolean)ret.get("mature")) == true){
System.out.println("mature is true !");
}
} catch (ParseException e) {
}
But, really, you shouldn't do this, and use an already existing JSON parser, because this code will break on any complex or invalid JSON data (like a ":" in the key), and if you want to build a true JSON parser by hand, it will take you a lot more code and debugging !
This is a parser of an easy json string:
public static HashMap<String, String> parseEasyJson(String json) {
final String regex = "([^{}: ]*?):(\\{.*?\\}|\".*?\"|[^:{}\" ]*)";
json = json.replaceAll("\n", "");
Matcher m = Pattern.compile(regex).matcher(json);
HashMap<String, String> map = new HashMap<>();
while (m.find())
map.put(m.group(1), m.group(2));
return map;
}
Live Demo

How do I remove a specific element from a JSONArray?

I am building one app in which I request a PHP file from server. This PHP file returns a JSONArray having JSONObjects as its elements e.g.,
[
{
"uniqid":"h5Wtd",
"name":"Test_1",
"address":"tst",
"email":"ru_tst#tst.cc",
"mobile":"12345",
"city":"ind"
},
{...},
{...},
...
]
my code:
/* jArrayFavFans is the JSONArray i build from string i get from response.
its giving me correct JSONArray */
JSONArray jArrayFavFans=new JSONArray(serverRespons);
for (int j = 0; j < jArrayFavFans.length(); j++) {
try {
if (jArrayFavFans.getJSONObject(j).getString("uniqid").equals(id_fav_remov)) {
//jArrayFavFans.getJSONObject(j).remove(j); //$ I try this to remove element at the current index... But remove doesn't work here ???? $
//int index=jArrayFavFans.getInt(j);
Toast.makeText(getParent(), "Object to remove...!" + id_fav_remov, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How do I remove a specific element from this JSONArray?
Try this code
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);
Edit:
Using ArrayList will add "\" to the key and values. So, use JSONArray itself
JSONArray list = new JSONArray();
JSONArray jsonArray = new JSONArray(jsonstring);
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i != position)
{
list.put(jsonArray.get(i));
}
}
}
In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove() method if you are targeting for Android API-18 or less. The remove() method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray to create a compatible override for the remove() method.
public class MJSONArray extends JSONArray {
#Override
public Object remove(int index) {
JSONArray output = new JSONArray();
int len = this.length();
for (int i = 0; i < len; i++) {
if (i != index) {
try {
output.put(this.get(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
return output;
//return this; If you need the input array in case of a failed attempt to remove an item.
}
}
EDIT
As Daniel pointed out, handling an error silently is bad style. Code improved.
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}
JSONArray jArray = new JSONArray();
jArray.remove(position); // For remove JSONArrayElement
Note :- If remove() isn't there in JSONArray then...
API 19 from Android (4.4) actually allows this method.
Call requires API level 19 (current min is 16): org.json.JSONArray#remove
Right Click on Project Go to Properties
Select Android from left site option
And select Project Build Target greater then API 19
Hope it helps you.
i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :
public Object remove(int index) {
Object o = this.opt(index);
this.myArrayList.removeElementAt(index);
return o;
}
In java version they use ArrayList, in ME Version they use Vector.
You can use reflection
A Chinese website provides a relevant solution: http://blog.csdn.net/peihang1354092549/article/details/41957369
If you don't understand Chinese, please try to read it with the translation software.
He provides this code for the old version:
public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
if(index < 0)
return;
Field valuesField=JSONArray.class.getDeclaredField("values");
valuesField.setAccessible(true);
List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
if(index >= values.size())
return;
values.remove(index);
}
In my case I wanted to remove jsonobject with status as non zero value, so what I did is made a function "removeJsonObject" which takes old json and gives required json and called that function inside the constuctor.
public CommonAdapter(Context context, JSONObject json, String type) {
this.context=context;
this.json= removeJsonObject(json);
this.type=type;
Log.d("CA:", "type:"+type);
}
public JSONObject removeJsonObject(JSONObject jo){
JSONArray ja= null;
JSONArray jsonArray= new JSONArray();
JSONObject jsonObject1=new JSONObject();
try {
ja = jo.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i=0; i<ja.length(); i++){
try {
if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
{
jsonArray.put(ja.getJSONObject(i));
Log.d("jsonarray:", jsonArray.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
jsonObject1.put("data",jsonArray);
Log.d("jsonobject1:", jsonObject1.toString());
return jsonObject1;
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
To Remove some element from Listview in android then it will remove your specific element and Bind it to listview.
BookinhHistory_adapter.this.productPojoList.remove(position);
BookinhHistory_adapter.this.notifyDataSetChanged();
We can use iterator to filter out the array entries instead of creating a new Array.
'public static void removeNullsFrom(JSONArray array) throws JSONException {
if (array != null) {
Iterator<Object> iterator = array.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o == null || o == JSONObject.NULL) {
iterator.remove();
}
}
}
}'
static JSONArray removeFromJsonArray(JSONArray jsonArray, int removeIndex){
JSONArray _return = new JSONArray();
for (int i = 0; i <jsonArray.length(); i++) {
if (i != removeIndex){
try {
_return.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return _return;
}

Categories

Resources