-1

I'm working in a project where after retrieving JSON from a URL, I need to manipulate the JSON file. I retrieved my JSON file from the following link:

http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313

That JSON file contains information on a specific Service Station in France such as:

  1. The Station Service details (steet,name,mark ...)
  2. The Services (Washing,WC ....)
  3. And the most importantly! The recent price of fuels

For that, I've tried to follow a solution given here at stackoverflow, by other user, to a similar problem. You can see:

Android JSON parsing of multiple JSONObjects inside JSONObject

Here is my code (full method):

 @GET
    @Path("/DecouvrirJSONInfo/{stationServiceInfo}")
    public StationService DecouvrirJSON(@PathParam ("stationServiceInfo") String jsonString) throws JSONException
    {

        JSONObject myResponse = new JSONObject(jsonString);
        String nom; 
        String carburantGazole, carburantSP95, carburantSP98, carburantGPL;
        float prixCarburantGazole, prixCarburantSP95, prixSP98, prixGPL; 
        Date dtActGazole, dtActSP98, dtActSP95,dtActGPL;
        StationService actuelStationService = new StationService();
        Carburant carburant = new Carburant();
        List<Carburant> carburants = new ArrayList<Carburant>();


        try
        {
            //nom = myResponse.getString("nom");
            Iterator<String> keysRoot = myResponse.keys();
            while (keysRoot.hasNext())
            {


                String rootKey = keysRoot.next();
                if(rootKey == "properties")
                {
                    JSONObject innerZeroJObject = myResponse.getJSONObject(rootKey);
                    Iterator<String> keys = innerZeroJObject.keys();
                    while( keys.hasNext() )
                    {

                        String key = keys.next();
                        //Log.v("**********", "**********");
                        //Log.v("category key", key);

                        if(key=="carburant")
                        {
                            JSONObject innerJObject = myResponse.getJSONObject(key);
                            Iterator<String> innerKeys = innerJObject.keys();
                            while( innerKeys.hasNext() )
                            {
                                String innerKkey = keys.next();
                                if(innerKkey == "1") // gazole
                                {
                                    JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
                                    Iterator<String> innerIKeys = innerIIJObject.keys();
                                    while( innerIKeys.hasNext() )
                                    {

                                        carburantGazole = innerIIJObject.getString("carburant");
                                        dtActGazole = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                                                    .parse(innerIIJObject.getString("maj"));
                                        prixCarburantGazole = Float.parseFloat( innerIIJObject.getString("prix"));
                                        carburant.DefinirNomCarburant(carburantGazole);
                                        carburant.DefinirPrixCarburant(prixCarburantGazole);
                                        carburants.add(carburant);
                                        carburant = new Carburant();
                                    }

                                }
                                else if(innerKkey == "2") // Sp95
                                {
                                    JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
                                    Iterator<String> innerIKeys = innerIIJObject.keys();
                                    while( innerIKeys.hasNext() )
                                    {
                                        carburantSP95 = innerIIJObject.getString("carburant");
                                        dtActSP95 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                                                    .parse(innerIIJObject.getString("maj"));
                                        prixCarburantSP95 = Float.parseFloat( innerIIJObject.getString("prix"));
                                        carburant.DefinirNomCarburant(carburantSP95);
                                        carburant.DefinirPrixCarburant(prixCarburantSP95);
                                        carburants.add(carburant);
                                        carburant = new Carburant();

                                    }

                                }
                                else if(innerKkey == "3") // SP98
                                {
                                    JSONObject innerIIJObject = myResponse.getJSONObject(innerKkey);
                                    Iterator<String> innerIKeys = innerIIJObject.keys();
                                    while( innerIKeys.hasNext() )
                                    {
                                        carburantSP98 = innerIIJObject.getString("carburant");
                                        dtActSP98 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                                                    .parse(innerIIJObject.getString("maj"));
                                        prixSP98 = Float.parseFloat( innerIIJObject.getString("prix"));
                                        carburant.DefinirNomCarburant(carburantSP98);
                                        carburant.DefinirPrixCarburant(prixSP98);
                                        carburants.add(carburant);
                                        carburant = new Carburant();    
                                    }

                                }
                                //String value = innerJObject.getString(innerKkey);
                                //Log.v("key = "+key, "value = "+value);
                            }
                        }

                    }
                }


            }

           //actuelStationService.DefinirNomStationService(nom);
           actuelStationService.DefinirCarburants(carburants);


        }
        catch(Exception ex)
        {

        }

        return actuelStationService;
    }

Can you help me and find the error(s). Please see the first link, which contains the JSON response.

suenda
  • 773
  • 1
  • 8
  • 21
Vitor Ferreira
  • 163
  • 1
  • 3
  • 11

1 Answers1

0

I would recommend using library like JsonPath to search through the json instead of iterating manually. If you can use JsonPath in your project, here is a way to do this:

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;

public class SearchJson {

    public static void main(String[] args) throws Exception {

        URL url = new URL("http://api.openeventdatabase.org/event/b2e7df60-3f25-4d80-b7ac-cffc10dd5313");
        URLConnection connection = url.openConnection();
        String jsonString = toString(new InputStreamReader(connection.getInputStream()));

        Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonString);

        Integer nbDesCarburants = (Integer) JsonPath.read(document, "$.properties.carburants.length()");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Carburant> carburants = new ArrayList<>();
        for (int i = 0; i < nbDesCarburants; i++) {
            Map<String, Object> carburantMap = (Map<String, Object>) JsonPath.read(document,
                    "$.properties.carburants[" + i + "]");
            String nom = (String) carburantMap.get("carburant");
            Date maj = simpleDateFormat.parse(carburantMap.get("maj").toString());
            float prix = Float.parseFloat(carburantMap.get("prix").toString());
            Carburant carburant = new Carburant(nom, maj, prix);
            carburants.add(carburant);
        }


        for (Carburant carburant : carburants) {
            System.out.println(carburant);
        }

    }

    static class Carburant {
        private final String nom;
        private final Date date;
        private final float prix;
        public Carburant(String nom, Date date, float prix) {
            super();
            this.nom = nom;
            this.date = date;
            this.prix = prix;
        }
        @Override
        public String toString() {
            return "Carburant [nom=" + nom + ", date=" + date + ", prix=" + prix + "]";
        }

    }

    public static String toString(InputStreamReader reader) throws IOException {
        char[] charBuf = new char[1024];
        int read = reader.read(charBuf, 0, 1024);
        StringBuilder sb = new StringBuilder();
        while (read != -1) {
            sb.append(new String(charBuf));
            charBuf = new char[1024];
            read = reader.read(charBuf, 0, 1024);
        }
        sb.append(new String(charBuf));
        return sb.toString();
    }

}

To run the example, make sure you have JsonPath jar in your classpath or if you are using maven to build your project, add json-path in your dependencies.

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.3.0</version>
</dependency>
suenda
  • 773
  • 1
  • 8
  • 21