1

I am beginner. I have MongoDB running. My task is to insert Student.json file on to MongoDB through java code and not through mongoimport.

Student.java

public class Student {

@Id
private ObjectId Id;

private long studentId;
private String studentName;
private String qualification;

public Student(){

}

public Student(long studentId, String studentName, String qualification) {
    this.studentId = studentId;
    this.studentName = studentName;
    this.qualification = qualification;
}

public long getStudentId() {
    return studentId;
}

public void setStudentId(long studentId) {
    this.studentId = studentId;
}

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public String getQualification() {
    return qualification;
}

public void setQualification(String qualification) {
    this.qualification = qualification;
}
}

Student.json

[{
     "studentId": 1,
     "studentName": "Shreyas",
     "qualification": "B.E"
},
{
     "studentId": 2,
     "studentName": "Yashas",
     "qualification": "B.Tech"
}]

UpdateSudentModel.java

public class UpdateStudentModel {

private static UpdateStudentModel USM;
private StudentRepo sr;


public static void main(String[] args) {
    // TODO Auto-generated method stub

    try{

        File file = new File("/home/bshreyasrao/Student.json");


        Injector injector = Guice.createInjector(new BindingModules());
        StudentRepo sr = injector.getInstance(StudentRepo.class);

        USM = new UpdateStudentModel(sr);
        USM.importFromJsonToMongoDB(file);
        } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error while injecting/File is not present");
        }       
}

public UpdateStudentModel(StudentRepo sr)
{
    this.sr = sr;
}

public void importFromJsonToMongoDB(File file){

    try{
        JsonParser parser = new JsonFactory().createParser(file);
        ObjectMapper mapper = new ObjectMapper();
        Iterator<Student> iterator = mapper.readValues(parser, Student.class);

         while(iterator.hasNext()) {
             sr.save(iterator.next());
            }
    }catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error While parsing data");
    }
}
}

Error

com.fasterxml.jackson.databind.RuntimeJsonMappingException: Can not deserialize instance of com.shreyas.student.model.Student out of START_ARRAY token
 at [Source: /home/bshreyasrao/Student.json; line: 1, column: 1]
    at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:194)
    at com.shreyas.student.UpdateStudentModel.importFromJsonToMongoDB(UpdateStudentModel.java:55)
    at com.shreyas.student.UpdateStudentModel.main(UpdateStudentModel.java:34)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.shreyas.student.model.Student out of START_ARRAY token
 at [Source: /home/bshreyasrao/Student.json; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:216)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:873)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:869)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1293)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:135)
    at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:277)
    at com.fasterxml.jackson.databind.MappingIterator.next(MappingIterator.java:192)
    ... 2 more
Error While parsing data

Things I tried

  • In Student.json if i remove "[" , "]" and "," which separates 2 json objects then my above code UpdateStudentModel.java works fine.

{"studentId": 1,"studentName": "Shreyas","qualification": "B.E"} {"studentId": 2,"studentName": "Yashas","qualification": "B.Tech"}

I know this is not valid JSON format.

  • So in order to be successful with valid JSON file how should i handle these "[" , "]" and "," ?

  • What changes i should do in the code?....pls pls help me in this regards..

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Shreyas Rao B
  • 193
  • 4
  • 17

1 Answers1

0

In your code you're expecting a Student object. But your JSON is a Student array. Can you try to change your code as expecting JSON array?

Change this line:

Iterator<Student> iterator = mapper.readValues(parser, Student.class);

as following:

Student[] iterator = mapper.readValues(parser, Student[].class);

OR

List<Student> iterator = mapper.readValues(parser, new TypeReference<List<Student>>.class);
ykaragol
  • 6,139
  • 3
  • 29
  • 56
  • When i replaced my code with your 2nd code it is showing **Syntax error on tokens, PrimitiveType expected instead** error. – Shreyas Rao B Apr 05 '16 at 05:28
  • Is there a way in which i can make use of JsonReader and add it to mongoDB? I am having problem with square brackets and comma. @ykaragol – Shreyas Rao B Apr 05 '16 at 05:33
  • * If i give you the same **Student.json** file, how will you read it from file?, how will you parse it ?, and finally how you would add it to mongoDB? Can you pls write up the code were it does all these things? – Shreyas Rao B Apr 05 '16 at 06:03
  • I never got this exception. Can you look at [this post](http://stackoverflow.com/questions/7246157/how-to-parse-a-json-string-to-an-array-using-jackson) – ykaragol Apr 05 '16 at 06:05
  • I changed from **mapper.readValues(parser,new TypeReference>.class)** to **mapper.readValues(parser,new TypeReference>() {})** now its showing some different error. The error is **The method readValues(JsonParser, Class) in the type ObjectMapper is not applicable for the arguments (JsonParser, new TypeReference>(){})** – Shreyas Rao B Apr 05 '16 at 06:38
  • My situation is similar to this (http://stackoverflow.com/questions/10926353/how-to-read-json-file-into-java-with-simple-json-library) – Shreyas Rao B Apr 05 '16 at 07:00
  • Sir can you show how i could implement JSONArray for the above code?I was going through JSONArray and I am using Jackson. – Shreyas Rao B Apr 05 '16 at 09:17