Object Mapper Values Returning Null - java

I'm using an Ajax Post request using jQuery to send data to Spring MVC. Two of those values are String data types while the other two are int. I get the following error: Can not instantiate variable of type.....From Integral number...
I'm receiving the data I sent from the client side into my server side Java code, but the values with the object mapper are null (i.e. personid = om.readValue(id, MyClass.class);) And those same lines are where the error points to. Changing Map<String,String> to be Map<String, Object> will not work either.
Below is my code. Any help would be greatly appreciated.
JSON:
{
id:"35",
firstname : "John",
lastname : "Doe",
age: "40"
}
Controller:
#RequestMapping(value="/mywebservice", method = RequestMethod.POST)
public Object getPerson(#RequestBody Map<String, String> mydata){
MyClass personid = null;
MyClass fname = null;
MyClass lname = null;
MyClass personage = null;
String id = "";
String firstname = "";
String lastname = "";
String age = "";
ObjectMapper om = new ObjectMapper();
if(mydata.containsKey("id"){
id = mydata.get("id");
}
if(mydata.containsKey("firstname"){
firstname = mydata.get("firstname");
}
if(mydata.containsKey("lastname"){
lastname = mydata.get("lastname");
}
if(mydata.containsKey("age"){
age = mydata.get("age");
}
try{
personid = om.readValue(id, MyClass.class);
fname = om.readValue(firstname, MyClass.class);
lname = om.readValue(lastname, MyClass.class);
personage = om.readValue(age, MyClass.class);
}catch(Exception e){ ...}
return helperClass(personid, fname, lname, personage);
}
Helper Class:
public Object getFirstName(MyClass personid, MyClass fname, MyClass lname, MyClass personage){
return addName(personid, fname, lname, personage);
}
Model:
#JsonProperty("id")
private int childid;
#JsonProperty("firstname")
private String firstname;
#JsonProperty("lastname")
private String lastname;
#JsonProperty("age")
private int childage;

Try change the json?
{
id:35,
firstname : "John",
lastname : "Doe",
age: 40
}

Related

how to convert json?

I want to convert firstname and lastname to json format.
#RestController
public class studentsController {
#GetMapping(value = "/students", produces = { MediaType.APPLICATION_JSON_VALUE } )
#ResponseBody
public String getWhoami(#RequestParam String firstname, #RequestParam String lastname ) {
return "firstname:" + firstname + " lastname: " + lastname;
}
}
How can I convert like these format;
{"firstname": "value1", "lastname": "value2"}
I tried to jackson but I couldn't.
You don't have to create json manually.
Create a class like:
class Student {
private String firstname;
private String lastname;
public Student(String firstname, String lastname) {
this.firstname = firstname;
this.lastname =lastname;
}
// getters and setter
}
#GetMapping(value = "/students", produces = { MediaType.APPLICATION_JSON_VALUE } )
#ResponseBody
public Student getWhoami(#RequestParam String firstname, #RequestParam String lastname ) {
return new Student(firstname, lastname);
}
You object will be converted to json automatically.
have you tried the jackson like this?
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
add in your class an instance like this:
ObjectMapper mapper = new ObjectMapper();
private ObjectMapper mapper = new ObjectMapper();
try function from the instance like this:
String jsonstr = mapper.writeValueAsString(object);
Lets say you already have the jackson library in your project (the jar file)
here's sample class:
public class SampleClass{
private ObjectMapper mapper = new ObjectMapper();
public String sampleMethodToJSONString(Student student){
return mapper.writeValueAsString(student);
}
}
You can change the return data type to use Map<String, String> instead of String or use ResponseBody<?>

JSON deserialiser to set custom properties in POJO

I'm using Jackson for json mapping on java POJOs. What I want is to set two properties in POJO from a value in JSON by splitting the value.
{
"email": "xyz#hello.com",
}
and POJO is
public class TestPojo {
#JsonProperty("email")
private String emailAddress;
/*is there any annotation available that I can split the email
address with a delimiter which is '#' to first and second
properties*/
private String first; //gives value xyz
private String second;//gives value hello.com
}
Thanks for your help in advance.
You can hijack that logic in your public setter.
For instance:
class MyPojo {
// no need for this annotation here actually, covered by setter
// at least for deserialization
#JsonProperty
String email;
String first;
String last;
#JsonProperty("email")
public void setEmail(String email) {
this.email = email;
String[] split = email.split("#");
// TODO check length etc.
this.first = split[0];
this.last = split[1];
}
// just for testing
#Override
public String toString() {
return String.format(
"email: %s, first: %s, last: %s%n", email, first, last
);
}
}
Then, somewhere else...
String json = "{ \"email\": \"xyz#hello.com\"}";
ObjectMapper om = new ObjectMapper();
MyPojo pojo = om.readValue(json, MyPojo.class);
System.out.println(pojo);
Output
email: xyz#hello.com, first: xyz, last: hello.com

Java - Jackson JSON Library and ObjectMapper.readValue

I have the following json data (patients.json):
{
"A" : {
"name" : "Tom",
"age" : 12
},
"B" : {
"name" : "Jim",
"age" : 54
}
}
Using the Jackson JSON library, how can I get something like the following:
HashMap<String, ???> patients = objectMapper.readValue(new File("patients.json"), ???);
String Aname = patients.get("A").get("name");
int Aname = patients.get("A").get("age");
Deserialize your JSON into Jackson's JSON Object type, ObjectNode. You can then traverse it as you see fit.
For example
ObjectNode patients = objectMapper.readValue(new File("test.json"), ObjectNode.class);
// you can check if it is actually an ObjectNode with JsonNode#isObject()
ObjectNode nodeA = (ObjectNode)patients.get("A");
String name = nodeA.get("name").asText();
int age = (int) nodeA.get("age").asLong();
Note that the methods asXyz() return default values if the target node cannot be converted to that type. You can check with the corresponding isXyz() methods before invoking them.
You could create a class to map your patients to;
private static class Patient {
#JsonProperty("name")
private String name;
#JsonProperty("age")
private int age;
public Patient() { }
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Then read your json into it via jackson
HashMap<String, Patient> patients = objectMapper.readValue(new File("patients.json"), new TypeReference<HashMap<String,Patient>>() {});
Patient patientA = patients.get("A");
String patientAName = patientA.getName();
int pateintAAge = patientA.getAge();

Attribute name in variable

;How can I use the value of a String variable as attribute or method name?
Want to do something like that:
class Person {
public String firstname;
}
String myAttributeName="firstname";
Person obj = new Person();
String firstNameOfObj = obj.{myAttributeName};
if you really want to do this, you could use reflection:
Person obj = new Person();
Method method = Person.class.getMethod("getFirstname");
String firstname = method.invoke(obj);
but as mentioned in the comments, you better use a map to hold attribute values:
class Person {
private Map<String,Object> attrs = new HashMap<>();
public void setAttribute(String attr, Object value)
{
attrs.put(attr,vaue);
}
public Object getAttribute(String attr)
{
attrs.get(attr);
}
}
Person person = new Person();
person.setAttribute("firstname","patrick");
String firstname = (String)person.getAttribute("firstname");

Mapping relational DB to a List<Object> each containing a List<Object> using JdbcTemplate

I am using Spring MVC with JdbcTemplate and a MySQL database.
Say I have the following 2 tables :
table_school
ID NAME
table_students
ID NAME ADDRESS SCHOOL_ID
I have a School POJO that has the following class variables :
int id, String name, List<Student> students
Is there a way of retrieving a List with each School object containing the appropriate List of Student objects using JdbcTemplate in one query? I know this is easily achievable using Hibernate but I would like to use JdbcTemplate ..
Many thanks !
Yes, you can fetch all data in 1 query.
Simple example:
class Student {
int id;
String name;
String addr;
Student(int id, String name, String addr) {
this.addr = addr;
this.id = id;
this.name = name;
}
}
class School {
int id;
String name;
List<Student> students = new ArrayList<>();
School(int id, String name) {
this.id = id;
this.name = name;
}
void addStudent(Student s) {
students.add(s);
}
}
/*
* helper method that gets school from map or create if not present
*/
private School getSchool(Map<Integer, School> schoolMap, int id, String name) {
School school = schoolMap.get(id);
if (school == null) {
school = new School(id, name);
schoolMap.put(id, school);
}
return school;
}
// RUN QUERY
String sql =
" select st.ID, st.NAME, st.ADDRESS. s.id, s.name" +
" from table_students st" +
" inner join table_school s on st.school_id = s.id";
final Map<Integer, School> schoolMap = new HashMap<>();
jdbcTemplate.query(sql, new RowCallbackHandler() {
#Override
public void processRow(ResultSet rs) throws SQLException {
int studentId = rs.getInt(1);
String studentName = rs.getString(2);
String studentAddr = rs.getString(3);
int schoolId = rs.getInt(4);
String schoolName = rs.getString(5);
Student student = new Student(studentId, studentName, studentAddr);
getSchool(schoolMap, schoolId, schoolName).addStudent(student);
}
});
One final point regarding fetching performance:
If you expect many records to fetch it is nearly always a good idea to increase jdbc fetch size parameter. So before run query set it on your jdbcTemplate:
jdbcTemplate.setFetchSize(200); // you can experiment with this value
or if you are using spring's JdbcDaoSupport you can use such pattern:
public class MyDao extends JdbcDaoSupport {
....
#Override
protected void initTemplateConfig() {
getJdbcTemplate().setFetchSize(200);
}
}

Categories