将URL中的JSON数据存储到MongoDB中

时间:2019-04-10 11:51:22

标签: java json mongodb

我想将数据存储到mongoDB的集合中,并在运行代码时将其存储在唯一的文档中

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException,
JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

public static void main(String[] args) throws IOException,
JSONException {
    JSONObject json = readJsonFromUrl("https://opendata.paris.fr/api/records/1.0/search/? 
    dataset = referentiel - comptages - routiers & rows = 10 ");
    //  System.out.println(json.toString());

    ObjectMapper mapper = new ObjectMapper();
    Map < String,
    Object > map = mapper.readValue(
    json.toString(), new TypeReference < Map < String, Object >> () {});
    Set cles = map.keySet();
    Iterator it = cles.iterator();

    while (it.hasNext()) {
        Object cle = it.next(); // tu peux typer plus finement ici
        Object valeur = map.get(cle); // tu peux typer plus finement ici
        System.out.println(valeur);
        MongoClient mongoClient = new MongoClient();

        DBObject infoClimatData = new BasicDBObject().append("cle", cle).append("data", valeur.toString());

        DB database = mongoClient.getDB("refGeoData");
        DBCollection collection = database.getCollection("refGeo");
        collection.insert(infoClimatData);
    }

}

这是我获取数据的方式:

enter image description here

所以我想浏览从url获得的结果以具有每个独立的字段,以便以适当的方式将其存储在数据库中。

0 个答案:

没有答案