从JSON文档中检索三个元素

时间:2018-02-08 18:37:15

标签: java json rest jax-rs

我正在一个项目中工作,从URL中检索JSON后,我需要操作JSON文件。我从以下链接检索了我的JSON文件:

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

该JSON文件包含有关法国特定服务站的信息,例如:

  1. 车站服务详情(街道,名称,标记......)
  2. 服务(洗衣,厕所......)
  3. 最重要的是!最近的燃料价格
  4. 为此,我尝试按照其他用户在stackoverflow上给出的解决方案来解决类似的问题。你可以看到:

    Android JSON parsing of multiple JSONObjects inside JSONObject

    这是我的代码(完整方法):

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

    你能帮助我并找到错误吗?请参阅第一个包含JSON响应的链接。

1 个答案:

答案 0 :(得分:0)

我建议使用像JsonPath这样的库来搜索json而不是手动迭代。如果您可以在项目中使用JsonPath,可以使用以下方法:

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

}

要运行该示例,请确保您的类路径中有JsonPath jar,或者如果您使用maven构建项目,请在依赖项中添加json-path。

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.3.0</version>
</dependency>