Grichka Grichka - 4 months ago 7
JSON Question

How can i remove a line in a JSON in JAVA

My JSON:

{
"adresses": [
{
"region": "Auvergne-Rhône-Alpes",
"pertinence": 0.41,
"cp": "73200",
"coordonnee": [
45.6681753,
6.3863336
],
"rue": "Rue Pasteur",
"osm_id": "8063355",
"pays": "France",
"ville": "Albertville",
"quartier": "Le Parstet",
"nom": "",
"secteur": "Albertville",
"numero": ""
},
{
"region": "Auvergne-Rhône-Alpes",
"pertinence": 0.41,
"cp": "73200",
"coordonnee": [
45.6635769,
6.3830012
],
"rue": "Rue Pasteur",
"osm_id": "69253010",
"pays": "France",
"ville": "Albertville",
"quartier": "",
"nom": "",
"secteur": "Albertville",
"numero": ""
},
{
"region": "Auvergne-Rhône-Alpes",
"pertinence": 0.41,
"cp": "73400",
"coordonnee": [
45.7469095,
6.4237485
],
"rue": "Rue Pasteur",
"osm_id": "170250718",
"pays": "France",
"ville": "Ugine",
"quartier": "",
"nom": "",
"secteur": "Albertville",
"numero": ""
}
]
}


I need to remove one of adresses when "osm_id" is equals to a variable.

I have started to put the JSON in a ArrayList string for delete the line I want then redo the JSON.
But element "coordonnee" is an array, and i don't know who can i do.

Here my trial :

JSONObject req = reponse.convertToJsonObject();
JSONArray adresses = req.getJSONArray( "adresses" );
ArrayList<String> tab = new ArrayList<String>();
for ( int i = 0; i < adresses.length(); i++ ) {
JSONObject adr = adresses.getJSONObject( i );
String line = adr.getString( "region" ) + " " + adr.getDouble( "pertinence" ) + " "
+ adr.getString( "cp" ) + " " + adr.getString( "coordonnee" )
+ " " + adr.getString( "rue" ) + " " + adr.getString( "osm_id" ) + " "
+ adr.getString( "pays" ) + " " + adr.getString( "ville" )
+ " " + adr.getString( "quartier" ) + " " + adr.getString( "nom" ) + " "
+ adr.getString( "secteur" ) + " " + adr.getString( "numero" );
tab.add( line );
}


Can you help me ?

Answer

I think this should do what you want. It will filter out any addresses that have an "osm_id" matching your provided variable.

JSONObject req = reponse.convertToJsonObject();
JSONArray filteredAddresses = new JSONArray();
String filterId = "..."; // put whatever your ID is here

JSONArray unfilteredAddresses = req.getJSONArray("adresses");
for (int i = 0; i < unfilteredAddresses.length(); i++){
    JSONObject addressJson = unfilteredAddresses.getJSONObject(i);
    if (!addressJson.has("osm_id") || !addressJson.getString("osm_id").equals(filterId)){
        filteredAddresses.put(addressJson);
    }
}
req.put("adresses", filteredAddresses);