how to autoGenearte _id instead of mongoDB ObjectId() - java

How to genearate "_id" : "01A63D2B-1724-456E-B2C0-3B3729951654" instead of "_id" : ObjectId("570602c46399e320c3022c6b")
My Student.class
#Entity("student")
public class Student {
#Id
private String 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;
}
}
Function to add JSON Data to MOngoDB:
public void importFromJsonToMongoDB(File file) throws FileNotFoundException{
try{
String strJson = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
JSONArray jsonArr = new JSONArray(strJson);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
String str = jsonObj.toString();
ObjectMapper mapper = new ObjectMapper();
Student std = mapper.readValue(str, Student.class);
sr.save(std);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error While parsing data");
}
* How to Auto Generate id? rather than MongoDb generating it.

I think you need to add "_id" field while inserting the document in MongoDB. since you are not specifying any "_id" field it will automatically be generated by MongoDB. You can also use getNextSequence() method of mongodb to generate the id according to your preference.
Note: StudentID and _id are two different entities in the same document.
I hope these link will be useful for you:
https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Replace the existing NO-arg Constructor with following one in
Student.class
public Student(){
super();
id = UUID.randomUUID().toString();
}
This will generate random id instead of MongoDB ObjectId

Related

How to valdiate each json array objects?

How to validate each of the names, ages and descriptions irrespective of json array index? It will kind of search that we need to validate on the basis of name, age and description with age is matching or not.
[
{
"Name": "Shobit",
"transactionDate": 1623049638000,
"age": "18",
"description": "My item for new collection addition into system with age 18"
},
{
"Name": "Neha",
"transactionDate": 1623049877000,
"age": "20",
"description": "My item for new collection addition into system with age 20"
}
]
You can convert your data to JSONArray and check each item as a JSONObject for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
Or move the validation to another method for example
JSONArray array = new JSONArray(data);
for(int i = 0; i < array.length() ; i++) {
JSONObject user = array.getJSONObject(i);
boolean isValidInfo = isValidateUser(user);
}
Validation method
public boolean isValidateUser(JSONObject user) {
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
}
For java you can use the library "org.json"
Add in your pom.xml dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Now you can use the next solution with java 8 :
JSONArray jsonArray = new JSONArray(yourJsonArray);
IntStream.range(0, jsonArray.length()).forEachOrdered(index -> {
// below the solution #AmrDeveloper
JSONObject user = jsonArray.getJSONObject(index);
String name = user.getString("Name");
long transactionDate = user.getLong("transactionDate");
int age = user.getInt("age");
String description = user.getString("description");
// Validate here
});
OR USE other libraries.
Example with Jackson
Add dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.2</version>
</dependency>
Create POJO:
public class User {
private String name;
private Long transactionDate;
private Integer age;
private String description;
public User(String name, Long transactionDate, Integer age, String description) {
this.name = name;
this.transactionDate = transactionDate;
this.age = age;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Long transactionDate) {
this.transactionDate = transactionDate;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Create method:
public <T> Optional<List<T>> buildListObjectsFromJson(String jsonObjectsList, Class<T> clazz) {
LOGGER.info("Try to build list objects from json....");
try {
ObjectMapper objectMapper = new ObjectMapper();
List<T> objectsList = objectMapper
.readValue(jsonObjectsList, objectMapper.getTypeFactory()
.constructCollectionType(ArrayList.class, clazz));
LOGGER.info("Objects list created successfully! List size = {}", objectsList.size());
return Optional.of(objectsList);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Can't build List objects by json: {}", jsonObjectsList);
}
return Optional.empty();
}
And create use next example:
List<User> users = buildListObjectsFromJson(yourJsonArray, User.class).orElse(new ArrayList<>());
This way you can work with this data as a collection.

how to convert a json file to some object calsses

I have a json file like this:
{
"Student" : [
{
"name": "john",
"age": 12
}, {
"name": "jack",
"age": 20
}
]
}
and my Student class is:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
I want to make a Student Instance with name "jack" by using json
how can I do it?
Make Another Class Students which contain List<Student>.
public class Students {
List<Student> Student;
public List<Student> getStudents() {
return Student;
}
public void setStudent(List<Student> students) {
this.Student=students;
}
}
Gson gson = new Gson();
String jsonString = "Your Json String";
Students student = gson.fromJson(jsonString, Students.class);
I use org.json.simple library when I parse JSON
Excample:
excample App.java,
excample Information.java
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}

OpenCSV memberFieldsToBindTo not working - Java

I am trying to use OpenCSV to parse a CSV file into a list of objects so I can load student data into my Student Team Allocator system.
I have been following this guide under the heading 'Parsing the records into a Java Object'
After some issues with dependencies I have it outputting a list of Student objects, however the CSV columns are not bound to the member fields as they should be. Print test returns null values for every object's fields.
I have two constructors in Student, one that initialises the 3 fields, and one that is empty. I know currently the empty one gets used as removing this one causes InstantiationExceptions in the Student object.
CSVParser Class
public class CSVParser {
private static String CSV_FILE_PATH;
public CSVParser(String CSVPath){
CSV_FILE_PATH = CSVPath;
try (
Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH));
) {
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(Student.class);
String[] memberFieldsToBindTo = {"fName", "sName", "stuNumber"};
strategy.setColumnMapping(memberFieldsToBindTo);
CsvToBean csvToBean = new CsvToBeanBuilder(reader)
.withMappingStrategy(strategy)
.withSkipLines(1)
.withIgnoreLeadingWhiteSpace(true)
.build();
List<Student> Students = csvToBean.parse();
for (Student s : Students) {
System.out.println("First Name : " + s.getFirstName());
System.out.println("Second Name : " + s.getSecondName());
System.out.println("StudentNo : " + s.getStudentNumber());
System.out.println("---------------------------");
}
} catch (IOException ex) {
Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Student Class
public class Student {
private String fName;
private String sName;
private String stuNumber;
private String skill;
private final String[] skills = {"Planning","Writing","Developing"};
public Student(){
}
public Student(String fName, String sName, String stuNumber) {
this.fName = fName;
this.sName = sName;
this.stuNumber = stuNumber;
}
// Setters
public void setSkill(int skillIndex){
this.skill = skills[skillIndex];
}
public void setFirstName(String fName){
this.fName = fName;
}
public void setSecondName(String sName){
this.sName = sName;
}
public void setStudentNumber(String stuNumber){
this.stuNumber = stuNumber;
}
// Getters
public String getFirstName(){
return fName;
}
public String getSecondName(){
return sName;
}
public String getStudentNumber(){
return stuNumber;
}
// Save to Database
private void saveStudent(){
// DBConnect db = new DBConnect();
}
}
The exception caused by non empty constructor
The print test showing null values in Student fields
Please let me know how I can make things any clearer,
Thanks.
The names in the column mapping array should respond to the names of the setters rather than the fields themselves. If it can't find a setter that correspond to the name, it can't set the value.

How to retrieve the result as JSON Arrray format in REST Response

I am trying to retrieve the data from database and return them in 'Response' as JSON array.
But now I am getting the result in browser as below, which is not the correct JSON array format. How can I receive the data as JSON Array ?
{"{\n \"id\": 14,\n \"name\": \"Test Doom Post\",\n \"email\": \"test#test1.com\...
JDK 1.7
Jersey (jaxrs-ri-2.25.1)
Gson
//Following is my Get method below:
#Path("/register")
public class JSONService {
#GET
#Path("/get")
#Produces("application/json")
#Consumes("application/json")
public Response getRegisterInJSON() {
JSONObject requestedJSON = new JSONObject();
try {
Class.forName("com.mysql.jdbc.Driver");
SoccerUtils dbConnection = new SoccerUtils();
Connection conn = dbConnection.getWeekendDBConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT ID, FIRST_NAME, EMAIL FROM mycoolmap.weekendsoccer_login");
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
RegisterPlayer playerObj = new RegisterPlayer();
playerObj.setId(rs.getInt("ID"));
playerObj.setName(rs.getString("FIRST_NAME"));
playerObj.setEmail(rs.getString("EMAIL"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json1 = gson.toJson(playerObj);
requestedJSON.put(json1, json1);
System.out.println(requestedJSON);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return Response.status(Status.OK).entity(requestedJSON.toString()).build();
}
// Register Player POJO class:
#XmlRootElement
public class RegisterPlayer implements Serializable {
private int id;
private String name;
private String email;
public RegisterPlayer() {
}
public RegisterPlayer(int id, String name, String email)
{
super();
this.id =id;
this.name = name;
this.email = email;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id =id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
#Override
public String toString() {
return "RegisterPlayer[id=" + id +", name=" + name +", email="+ email +"]";
}
}
As advised by Roman in above comment, I have created a list, add the object and return the list. It worked as expected.
/Created a 'registerPlayerList' List
List<RegisterPlayer> registerPlayerList = new ArrayList<RegisterPlayer>();
// Intialiaze the RegisterPlayer class
RegisterPlayer playerObj = new RegisterPlayer();
//set all the values into the object
playerObj.setId(rs.getInt("ID"));
playerObj.setName(rs.getString("FIRST_NAME"));
playerObj.setEmail(rs.getString("EMAIL"));
......
//add the playerObj to the created registerPlayerList
registerPlayerList.add(playerObj);
// return the list
return registerPlayerList ;
The problem is that you're printing the json to string (the json1 variable), but you're adding that string to a JSONObject. When a string is added to a JSONObject, the string will be escaped - that's a String json object.
If you print json1 instead (and set that as the entity), it should work.

how to make retrofit POJO class for this Json

here is the json form that i try to make pojo class for it
[{"ID":"1",
"SectionName":""
,"Title":"testosss"}
,{"ID":"2"
,"SectionName":"",
"Title":"test"}]
i have one array with list of object what should i do to make pojo class in this case ?
Generate pojo class using jsonschema2pojo
import java.util.HashMap;
import java.util.Map;
public class Example {
private String iD;
private String sectionName;
private String title;
public Example(){
}
public Example(String id,String sectionName,String title){
this.iD = id;
this.sectionName = sectionName;
this.title = title;
}
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
whenever you have multiple jsonArray value in your json data, we need to store all data in ArrayList. here i have make some code for you i hope might be helpful you.
Your json data
String jsonDemo = "[{\"ID\":\"1\",\n" +
"\"SectionName\":\"\"\n" +
",\"Title\":\"testosss\"}\n" +
",{\"ID\":\"2\"\n" +
",\"SectionName\":\"\",\n" +
"\"Title\":\"test\"}]";
for get josn data and store in ArrayList with Example pojo class
create ArrayList class with pojo model class
ArrayList<Example> arrayList = new ArrayList<>();
json parsing and store each data in arraylist
try {
JSONArray jsonArray = new JSONArray(jsonDemo);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String ID = jsonObject.getString("ID");
String sectionName = jsonObject.getString("SectionName");
String title = jsonObject.getString("Title");
arrayList.add(new Example(ID,sectionName,title));
}
} catch (JSONException e) {
e.printStackTrace();
}
Retrieve all json data
if(arrayList.size()>0){
for(int i=0;i<arrayList.size();i++){
Example example = arrayList.get(i);
Log.d("Example","ID : " + example.getID());
Log.d("Example","getSectionName : " + example.getSectionName());
Log.d("Example","getTitle : " + example.getTitle());
}
}

Categories

Resources