我有json值,如何使用spring mvc保存到mongodb中

时间:2016-06-28 15:13:53

标签: mongodb spring-mvc

我有类似“位置”的课程。 “位置”类有四个字段。 字段是:id,city,state,country .. country是seprate class它包含2个字段,国家代码,国家名称,2个字段必须从location class读取.. 如果我写“locationMongoRepository.save()”,它会将错误显示为绑定不匹配。请给出如何保存在mongodb的解决方案。

 public void insertLocation() throws InvalidFormatException, IOException, JSONException{



        FileInputStream inp;
        Workbook workbook;
        try {

        inp = new FileInputStream( "/home/Downloads/eclipse/Workspace/Samplboot-master latest/cityListForIndia1.xlsx" );
        workbook = WorkbookFactory.create( inp );
        Sheet sheet = workbook.getSheetAt(0);
        JSONArray json = new JSONArray();
        boolean isFirstRow = true;
        ArrayList<String> rowName = new ArrayList<String>();
        for ( Iterator<Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
        {
            Row row = rowsIT.next();
            JSONObject jRow = new JSONObject();


            if(isFirstRow)
            {
                for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
                {
                    Cell cell = cellsIT.next();

                    rowName.add(cell.getStringCellValue());


                }
            isFirstRow = false;
            }   
            else
            {
                JSONObject jRowCountry= new JSONObject();
                JSONObject jRowLocation= new JSONObject();

                jRowLocation.put("city", row.getCell(0));
                jRowLocation.put("state", row.getCell(1));
                jRowCountry.put("country",row.getCell(2) );
                jRowCountry.put("countryCode", row.getCell(3) );
                jRowLocation.put("country", jRowCountry);
                System.out.println("Location"+jRowLocation.toString()); 

            }


        }




    }
        catch (InvalidFormatException e) {
        // TODO Auto-generated catch block
        System.out.println("Invalid Format, Only Excel files are supported");
        e.printStackTrace();
        } catch (IOException e) {
        System.out.println("Check if the input file exists and the path is correct");
        e.printStackTrace();
        } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to generate Json");
        e.printStackTrace();
        } 

        }
    }

1 个答案:

答案 0 :(得分:3)

我使用Spring Data来支持使用MongoDB,它真的很有帮助。您应该阅读本文以了解其想法并将其应用于您的案例https://dzone.com/articles/spring-data-mongodb-hello

P / S:如果您无法使用Spring Data与MongoDB一起使用,请在您的代码/您的例外中提供更多详细信息,以便我们对其进行更详细的调查。