Cannot convert text file to json - java

hello am new to jackson and am trying to convert a text file into JSON but am having problem with my text file I dont know in what format the details of text file should be below is my code
ERROR : org.codehaus.jackson.map.JsonMappingException: Unrecognized field "Employee" (Class test.Employee), not marked as ignorable
at [Source: C:\Users\Ashwin Utchanah\Desktop\BIOGRID\jsonInput.txt; line: 3, column: 2]
text file : {"Employee":{"EmpID":1234,"name":"assd","designation":”programmer”,"salary":25000}}
Employee Class :
public class Employee {
private int empId;
private String name;
private String designation;
private String department;
private int salary;
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("************************************");
sb.append("\nempId: ").append(empId);
sb.append("\nname: ").append(name);
sb.append("\ndesignation: ").append(designation);
sb.append("\ndepartment: ").append(department);
sb.append("\nsalary: ").append(salary);
sb.append("\n************************************");
return sb.toString();
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Main Class :
public class ObjectToJson {
public static void main(String [] args) {
ObjectMapper mapper = new ObjectMapper();
try {
File jsonInputFile = new File("C:\\Users\\Ashwin Utchanah\\Desktop\\BIOGRID\\jsonInput.txt");
Employee emp = mapper.readValue(jsonInputFile, Employee.class);
System.out.println(emp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

The JSON you're trying to convert into a concrete object is not a valid one.
You can easily test this using a JSON validator like JSON lint.
https://jsonlint.com/
The problem occurs from the top level Employee field. Changing your input file to:
{
"EmpID": 1234,
"name": "assd",
"designation": "programmer",
"salary": 25000
}
Should fix your problem.

Related

Mapping java class To JSON By Using Jackson

I want to convert the following bean class to JSON object by using Jackson library
public class Student {
String name ;
int id ;
List<Address> address;
}
I want following json
{
"Name" : "sys1",
"Id" : 1,
"address" : [some address]
}
Can anyone help me how to achieve this ?.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaToJson {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Address> addrList = new ArrayList<>();
Address addr = new Address();
addr.setArea("ABC");
addr.setCity("XYZ");
addrList.add(addr);
Student std = new Student();
std.setName("Rahul");
std.setId(1);
std.setAddress(addrList);
String json = objectMapper.writeValueAsString(std);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int id;
List<Address> address;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
class Address {
String area;
String city;
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return this.area;
}
public void setCity(String city) {
this.city = city;
}
}

How to map string json to POJO class?

I have a body return this:
{
"a_name": "Max",
"a_surname": "Miles",
"a_details": {
"DETAILS": [
{
"DATE": "1996-12-31T00:00:00.000",
"AGE": "24",
"ACCNUM": "17",
"FORSPEC": "Smth written here",
"EXIT": "1"
}, ] //list of json
}
By now I am able to return name and surname, but having trouble mapping json field. Here is how my POJO looks like:
class Value {
String name;
String surname;
List<AccountDetail> detail;
//setter getter
}
class AccountDetail {
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
//setter getter
}
Here is a mapper for this field:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(
DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<AccountDetails> details = mapper.readValue(stringJson, Value.class);
But I am getting errors like unrecognized fields and so on. What is a problem? Maybe I should realize my POJO class in other way or I have a problem with mapper?
You can use Jackson library for Json reading, and use annotation for different name #JsonProperty("a_name")
Few more issues I found in your code:
This is incorrect - List<AccountDetail> detail
You should declare a field DETAILS, as a new class, and inside should be the list.
Also "EXIT" field is missing in the class you defined.
Full working example.
public String test() throws JsonProcessingException
{
String json = "your json here....";
ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultPrettyPrinter(new PrettyPrinter());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping();
mapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
mapper.readValue(json, Value.class);
return "success";
}
public static class PrettyPrinter extends DefaultPrettyPrinter
{
private static final long serialVersionUID = 1L;
public PrettyPrinter()
{
indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
}
}
private static class Value
{
#JsonProperty("a_name")
String name;
#JsonProperty("a_surname")
String surname;
#JsonProperty("a_details")
Details details;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public Details getDetails()
{
return details;
}
public void setDetails(Details details)
{
this.details = details;
}
}
private static class Details
{
#JsonProperty("DETAILS")
AccountDetail []detail;
public AccountDetail[] getDetail()
{
return detail;
}
public void setDetail(AccountDetail[] detail)
{
this.detail = detail;
}
}
private static class AccountDetail
{
LocalDateTime DATE;
Number AGE;
Number ACCNUM;
String FORSPEC;
Number EXIT;
public LocalDateTime getDATE()
{
return DATE;
}
public void setDATE(LocalDateTime DATE)
{
this.DATE = DATE;
}
public Number getAGE()
{
return AGE;
}
public void setAGE(Number AGE)
{
this.AGE = AGE;
}
public Number getACCNUM()
{
return ACCNUM;
}
public void setACCNUM(Number ACCNUM)
{
this.ACCNUM = ACCNUM;
}
public String getFORSPEC()
{
return FORSPEC;
}
public void setFORSPEC(String FORSPEC)
{
this.FORSPEC = FORSPEC;
}
public Number getEXIT()
{
return EXIT;
}
public void setEXIT(Number EXIT)
{
this.EXIT = EXIT;
}
}
You can used Gson library
public class JsonFormater {
public static void main(String[] args) {
Gson gs = new Gson();
// TODO Auto-generated method stub
String jsonstring = "{\n" + " \"a_name\":\"Max\",\n" + " \"a_surname\":\"Miles\",\n"
+ " \"a_details\":{\n" + " \"DETAILS\":[\n" + " {\n"
+ " \"DATE\":\"1996-12-31T00:00:00.000\",\n" + " \"AGE\":\"24\",\n"
+ " \"ACCNUM\":\"17\",\n" + " \"FORSPEC\":\"Smth written here\",\n"
+ " \"EXIT\":\"1\"\n" + " }\n" + " ]\n" + " }\n" + "}";
Information infomation = gs.fromJson(jsonstring, Information.class);
System.out.println(infomation.getaName());
System.out.println(infomation.getaSurname());
if (infomation.getaDetails() != null) {
TestData testdata = infomation.getaDetails();
for (Detail detail : testdata.getDetails()) {
System.out.println(detail.getAge());
}
}
}
}
public class Detail {
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("AGE")
#Expose
private String age;
#SerializedName("ACCNUM")
#Expose
private String accnum;
#SerializedName("FORSPEC")
#Expose
private String forspec;
#SerializedName("EXIT")
#Expose
private String exit;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAccnum() {
return accnum;
}
public void setAccnum(String accnum) {
this.accnum = accnum;
}
public String getForspec() {
return forspec;
}
public void setForspec(String forspec) {
this.forspec = forspec;
}
public String getExit() {
return exit;
}
public void setExit(String exit) {
this.exit = exit;
}
}
public class TestData {
#SerializedName("DETAILS")
#Expose
private List<Detail> details = null;
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
}
public class Information {
#SerializedName("a_name")
#Expose
private String aName;
#SerializedName("a_surname")
#Expose
private String aSurname;
#SerializedName("a_details")
#Expose
private TestData aDetails;
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaSurname() {
return aSurname;
}
public void setaSurname(String aSurname) {
this.aSurname = aSurname;
}
public TestData getaDetails() {
return aDetails;
}
public void setaDetails(TestData aDetails) {
this.aDetails = aDetails;
}
}
format your json correctly and try like this

Not able to wrap JSON properties in a Custom Java Class in Jackson

I have a JSON string that needs to be converted to JAVA Object. I need to wrap some fields into a different JAVA class. The problem I am facing I am not able to wrap it and I get the Java fields as null.
Please see below JSON
{
"first_name": "John",
"last_name": "DCosta",
"age": "29",
"phone": "+173341238",
"address_line_1": "43 Park Street",
"address_line_2": "Behind C21 Mall",
"city": "Cario",
"country": "UK",
"child1": {
"name": "Peter",
"age": "5"
},
"child2": {
"name": "Paddy",
"age": "2"
},
"child3": {
"name": "Premus",
"age": "1"
}
}
Please see my JAVA Classes Below -
Details.java
public class Details {
private Person person;
private Address address;
private Child[] children;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Child[] getChildren() {
return children;
}
public void setChildren(Child[] children) {
this.children = children;
}
}
Person.java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
#JsonProperty("first_name")
private String firstName;
#JsonProperty("last_name")
private String lastName;
#JsonProperty("age")
private Integer age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Address.java
import com.fasterxml.jackson.annotation.JsonProperty;
public class Address {
#JsonProperty("phone")
private String phone;
#JsonProperty("address_line_1")
private String addressLine1;
#JsonProperty("address_line_2")
private String addressLine2;
#JsonProperty("city")
private String city;
#JsonProperty("country")
private String country;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Child.java
public class Child {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
My Code to convert JSON to JAVA Object -
String filePath = "test.json";
File file = new File(filePath);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Details details = mapper.readValue(file, Details.class);
System.out.println(details.getPerson());
The problem I am facing is I am getting all the values in the details object are null. If I remove the mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); then I get the below exception
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "first_name" (class learn.springboot.model.Details), not marked as ignorable (3 known properties: "address", "person", "children"])
at [Source: (File); line: 2, column: 17] (through reference chain: learn.springboot.model.Details["first_name"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.ja
I don't think that it is possible to have some wrapper classes and expect Jackson to flatten and extract all of those fields from wrapper classes and map the flat JSON fields to them.
Based on the Details class, Jackson expects having a JSON object like the below one (inner fields are omitted):
{
"person": {},
"address": {},
"children": []
}
So, you have to change the Details class to something like below:
public class Details {
#JsonProperty("first_name")
private String firstName;
#JsonProperty("last_name")
private String lastName;
#JsonProperty("age")
private Integer age;
...
}

Out of START_ARRAY token while reading a JSON in servlet

I have to create Java object from JSON string received in servlet
Below is the JSON
[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade#gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]
I tried to change the JSON that is by replacing [ by { and ] by } but it gives some other error.
My jackson code where I am getting exception is
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);
And the Enroll class is simple bean class with setter and getter
public class Enrole {
private String name;
private String email;
private long contactno;
private String address;
This is one of the way
try {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"name\",\"value\":\"Shital\"},{\"name\":\"email\",\"value\":\"swankhade#gmail.com\"},{\"name\":\"contactno\",\"value\":\"9920042776\"},{\"name\":\"Address\",\"value\":\"a6 102 Elementa\"}]";
KeyValue[] jsonObjArr = mapper.readValue(json, KeyValue[].class);
Enrole enrol = new Enrole();
for (int i = 0; i < jsonObjArr.length; i++) {
KeyValue keyVal = jsonObjArr[i];
if ("name".equals(keyVal.getName())) {
enrol.setName(keyVal.getValue());
}
if ("email".equals(keyVal.getName())) {
enrol.setEmail(keyVal.getValue());
}
if ("contactno".equals(keyVal.getName())) {
enrol.setContactno(Long.parseLong(keyVal.getValue()));
}
if ("address".equals(keyVal.getName())) {
enrol.setAddress(keyVal.getValue());
}
}
System.out.println(enrol.getName());
System.out.println(enrol.getContactno());
System.out.println(enrol.getAddress());
System.out.println(enrol.getEmail());
} catch (Exception e) {
System.out.println("Exception " + e);
}
Class with Key and Value :
class KeyValue {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Model Class
class Enrole {
private String name;
private String email;
private long contactno;
private String address;
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;
}
public long getContactno() {
return contactno;
}
public void setContactno(long contactno) {
this.contactno = contactno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

Java Json Jackson saving private fields without getters and setters

I am using Jackson to save my java object (Person.class) as a json file and load from it using jackson as well.
This is what I am saving at the moment:
public class Person {
private String name;
private int yearOfBirth;
public Person(String name, int yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYearOfBirth() {
return yearOfBirth
}
public void setYearOfBirth(int yearOfBirth) {
this.yearOfBirth = yearOfBirth;
}
}
Even though a person's name (in this case) CANNOT be changed, nor can their year of birth, I have to have the getters and setters for Jackson to recognise the values otherwise it will give an exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "name"
How can i make my fields name and yearOfBirth (without making them PUBLIC ofcourse) final fields uneditable after initialisation.
This is my saving and loading using jackson:
saving:
public void savePerson(File f, Person cache) {
ObjectMapper saveMapper = new ObjectMapper()
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
saveMapper.setVisibilityChecker(
saveMapper.getSerializationConfig().
getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).
withGetterVisibility(JsonAutoDetect.Visibility.NONE).
withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
);
ObjectWriter writer = saveMapper.writer().withDefaultPrettyPrinter();
writer.writeValue(f, cache);
}
loading:
public Person load(File f) {
return new ObjectMapper().readValue(f, Person.class);
}
User #JsonProperty and it will work.
import com.fasterxml.jackson.annotation.JsonProperty;
public class Person {
private final String name;
private final int yearOfBirth;
public Person(#JsonProperty("name") String name, #JsonProperty("yearOfBirth") int yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
}
public String getName() {
return name;
}
public int getYearOfBirth() {
return yearOfBirth;
}
}

Categories