How can I deserailize JSON to an inputbean using objectmapper? - java

I have a JSON String as below:
{
"PhoneNumber": "0000000000",
"cart":
[
{
"Number": "1234",
"realm": "2345",
"id": "1234",
"quantity": "1"
}
],
"employeeId": "345",
"group": "10080",
"empEmail": "xyz#gmail.com",
}
How can I deserailize to an inputbean using objectmapper?
inputBean = objectMapper.readValue(json.toString(), inputBean.getClass());
I am getting error like
Can not deserialize instance of java.lang.String[]
out of START_OBJECT token\n at

What is the class of inputBean?
To deserialise that JSON you'll need the following beans:
class InputBean {
String phoneNumber;
List<Cart> cart;
String employeeId;
String group;
String empEmail;
// Getters, setters and constructor omitted for brevity
}
class Cart {
String number;
String realm;
String id;
String quantity;
// Getters, setters and constructor omitted for brevity
}
You then deserialise it with:
InputBean inputBean = objectmapper.readValue(json.toString(), InputBean.class);
You should also take a look at your JSON source material because it's inconsistent in property naming with some properties beginning with an uppercase character and some with a lowercase character.

Related

Parsing of json response from REST API which has id as field name

I want to parse the json string and form a pojo object but the response is somewhat unusual.
I have folloing type of response from API
"data": {
"12": {
"value": "$0.00",
"order_id": "12",
"order_date": "2020-08-26 15:50:05",
"category_name": "Games",
"brand_id": "4",
"denomination_name": "AED 50",
"order_quantity": "1",
"vendor_order_id": "A-123",
"vendor_location": "",
"vouchers": {
"804873": {
"pin_code": "41110AE",
"serial_number": "fddfgfgf1234444"
}
}
},
"15": {
"value": "$0.00",
"order_id": "15",
"order_date": "2020-08-26 08:39:11",
"category_name": "Games",
"brand_id": "52",
"brand_name": "PlayStation",
"denomination_name": "$20",
"order_quantity": "1",
"vendor_order_id": "A-316",
"vendor_location": "",
"vouchers": {
"806328": {
"pin_code": "fdfd",
"serial_number": "fawwwww"
}
}
}
}
}
How do I parse this response since inside data the field name is order id same with voucher
If you use Jackson JSON library, you should have POJOs like those shown below and use PropertyNamingStrategy.SnakeCaseStrategy to handle property names in the input JSON:
// top-level container
public class Response {
private Map<Integer, Order> data;
// getter/setter
}
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Order {
private String value; // may be some Currency class
private Integer orderId;
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime orderDate;
private String categoryName;
private Integer brandId;
private String brandName;
private String denominationName; // may be Currency too
private Integer orderQuantity;
private String vendorOrderId;
private String vendorLocation;
private Map<Integer, Voucher> vouchers;
// getters/setters
}
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Voucher {
private String pinCode;
private String serialNumber;
// getters/setters
}

How to deserialize complex JSON to java object

I need to deserialize JSON to java class.
I have JSON like the following:
{
"data": {
"text": "John"
},
"fields":[
{
"id": "testId",
"name": "fieldName",
"options": {
"color": "#000000",
"required": true
}
},
{
"id": "testId",
"name": "fieldName1",
"options": {
"color": "#000000",
"required": false
}
}
]
}
and I need to deserialize this JSON (only "fields" section) to java class like the following:
public class Field {
public final String id;
public final String name;
public final String color;
public final boolean required;
}
and I need to get something like the following:
// The key is the id from field object (it can be the same in the multiple objects.)
Map<String, List<Field>> fields = objectMapper.readValue(json, Map<String, List<Field>>);
How can I do it using Jackson?
As long as jackson doesn't support #JsonWrapped, you have to use the following work around.
First you need to create a custom class which contains the fields:
public class Fields {
public List<Field> fields;
}
Depending on your ObjectMapper configuration you have to add #JsonIgnoreProperties(ignoreUnknown = true) to the Fields class, to ignore any other properties.
Next is that you have to define the nested Options class which is solely used temporarily:
public class Options {
public String color;
public boolean required;
}
And at last add this constructor to your Field class:
#JsonCreator
public Field(#JsonProperty("id") String id, #JsonProperty("name") String name, #JsonProperty("options") Options options){
this.id = id;
this.name = name;
this.color = options.color;
this.required = options.required;
}
The #JsonCreator annotation indicates to jackson that this constructor needs to be used for the deserialization. Also the #JsonProperty annotations are required as arguments to constructors and methods are not preserved in the bytecode
Then you can deserialize your json just like this:
List<Field> fields = objectMapper.readValue(json, Fields.class).fields;

Can i know if an object is a custom object?

I am writing an annotation processor and i need to scan all classes with certain annotation to get all fields and create json object with same structure of the class.
For example:
#ClassToJson
public class Person {
private String name;
private String surname;
/*getter and setter*/
}
My output is:
{
"name": "string",
"surname": "string"
}
Now i am wondering how can i handle classes like this one:
public class PhoneNumber {
private String countryCode;
private String phoneNumber;
/*getter and setter*/
}
#ClassToJson
public class Person {
private String name;
private String surname;
private PhoneNumber phoneNumber;
/*getter and setter*/
}
i would like get output like this:
{
"name": "string",
"surname": "string",
"phoneNumber": {
"countryCode": "string",
"phoneNumber": "string"
}
}

Deserialize an object with children

I have a Json list using object with children
{
"id":"154",
"name":"peter",
"children": [
{
"id":"122",
"name": "mick",
"children":[]
},
{
"id":"123",
"name": "mick",
"children":[]
}
]
}
Here is the class of my object:
public class person{
private String id;
private String name;
private List<person> children;
//getters and setters
}
When I try to deserialize this object, I have the following error
Can not deserialize instance of person out of START_ARRAY token
What should I do ?
The JSON contains an array of persons.
Your class a List of person.
Either change the JSON like #Naveed Yadav suggested or change the class to
public class Person{
private String id;
private String name;
private Person[] children;
//getters and setters
}
(BTW the class name should be upper case in Java)
Fix syntax errors in your JSON body and you'll be in a good shape:
{
"id":"154",
"name":"peter",
"children": [
{
"id":"122",
"name": "mick",
"children":[], <== Excess comma
} <== Missing comma
{
"id":"123",
"name": "mick",
"children":[], <== Excess comma
}
]
}
Valid one:
{
"id": "154",
"name": "peter",
"children": [{
"id": "122",
"name": "mick",
"children": []
},
{
"id": "123",
"name": "mick",
"children": []
}
]
}
You need to change your POJO declaration like below:-
public class person{
private String id;
private String name;
private List<Children> children;
//getters and setters
private class Children{
private String id;
private String name;
private String[] children;
}
{
"id":"154",
"name":"peter",
"children":
{
"id":"122",
"name": "mick",
"children":[],
}
{
"id":"123",
"name": "mick",
"children":[],
}
}

How to use Jackson ObjectMapper to parse json response to java objects

Here is my Json response
"postedevent": [
{
"status": "true",
"event_id": "800",
"num_of_image_event": "0",
"title": "Testy",
"photo": "http://54.200.110.49/checkplanner/img/upload/21310059819profile_image_1409303464798.png",
"event_date": "2014-08-29",
"fullDate": "Friday - August 29, 2014",
"event_from": "12:00AM",
"event_to": "12:15AM",
"city": "Ahm",
"state": "CA",
"member_id": "471",
"username": "Krishna Mohan",
"pencil": "yes",
"attend": "yes",
"company": "Development"
}
]
this is java class to get java objs from json response
public class PostedEvent {
String status;
int event_id;
int num_of_image_event;
String title;
String photo;
String event_date;
String fullDate;
String event_from;
String event_to;
String city;
String state;
String member_id;
String username;
String pencil;
String attend;
String company;
}
public class PostedEvnetsList
{
ArrayList<PostedEvent> postedevent;
}
And I am parsing in this way
InputStream is = WebResponse.getResponse(url);
ObjectMapper mapper = new ObjectMapper();
PostedEvnetsList mList = null;
mList = mapper.readValue(is,PostedEvnetsList.class);
eventList = mList.postedevent;
I am getting following parse exception
jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "status" (Class com.example.jsonproforexam.PostedEvent), not marked as ignorable
I have declared same fields as in json response then why I am geting this exception
Please help
Your fields of PostedEvent and the PostedEvent field of PostedEventsList are not accessible.
You must set them as public (not recommended) or provide public getters and setters for them POJO-style.
Then Jackson will be able to de-serialize and the error will go away.
You can use the JsonProperty annotation to specify the json key
Ex:
public class PostedEvent {
#JsonProperty("status")
String status;
#JsonProperty("event_id")
String eventId;
....
....
If you have missed some fields from json in your entity class, you can use #JsonIgnoreProperties annotation to ignore the unknown fields.
#JsonIgnoreProperties(ignoreUnknown = true)
public class PostedEvent {
...

Categories

Resources