I'm creating a REST service that receives a JSON input like this:
[
{
"person": {
"name": "string",
"surname": "string",
"address": "string",
"age": "data",
"info": {
"number": "string"
}
}
},
{
"person": {
"name": "string",
"surname": "string",
"address": "string",
"age": "data",
"info": {
"number": "string"
}
}
}
]
My items are(
I omitted getters and setters):
public class Request {
private List<Person> person;
}
public class Person{
private String name;
private String surname;
private String address;
private XMLGregorianCalendar age;
private Info info;
}
public class Info {
private String number;
}
how come i get the following error?
{
"timestamp": 1611142052198,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize instance of com.myproject.model.Request out of
START_ARRAY
}
i need the json structure to be exactly that.
You are trying to de-serialize your input array to a Request object, which is not a collection, and thus you get that error.
To solve it you should de-serialize your input array to a List<Person> object and then set that object to your Request object:
Request request = ... // get the request
List<Person> person = ... // deserialize the input array
request.setPerson(person);
If you are using Jackson, you can also define a constructor for your Request class which takes a List<Person> argument and then mark that constructor with the #JsonCreator annotation (see here for an example):
public class Request {
private List<Person> person;
#JsonCreator
public Request(#JsonProperty("person") List<Person> person) {
this.person = person;
}
}
And then you can create your Request object directly from your input array.
By using the #JsonCreator annotation you keep your Request class immutable, because you don't need to define a setPerson(List<Person>) method for it.
Related
I'm having problems parsing JSON, this is the error:
out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<packagename....>` out of START_OBJECT token
And I know why it is happening I just don't know how to fix it. This JSON works:
{
"status_code": "SUCCESS",
"time": {
"date": "Mar 23, 2021 1:14:39 AM"
},
"info": [
{
"person": "2.2",
"role": "TEACHER"
},
{
"person": "2.3",
"role": "TEACHER"
}
]
}
This one does not:
{
"status_code": "SUCCESS",
"time": {
"date": "Mar 23, 2021 3:49:27 AM"
},
"info": {
"id": "1",
"person": [
{
"identifier": "John",
"role": "TEACHER"
},
{
"identifier": "Homer",
"role": "TEACHER"
},
{
"identifier": "Michael",
"role": "TEACHER"
},
{
"identifier": "Sarah",
"role": "TEACHER"
}
]
}
}
The problem seems to be the { character in front of the info field because with [ works. So this is the method I'm using to parse the JSON:
public Mono<PersonResponse> searchById(String id) {
return webClient.get().uri(id).retrieve().bodyToMono(PersonResponse.class);
}
Also tried:
public Mono<PersonResponse[]> searchById(String id) {
return webClient.get().uri(id).retrieve().bodyToMono(PersonResponse[].class);
}
Error right on line: 1, column: 1. Any suggestions of how to implement the method?
EDIT: Added classes.
PersonResponse:
public class PersonResponse implements Serializable{
private static final long serialVersionUID = 7506229887182440471L;
public String status_code;
public Timestamp time;
public List<PersonDetails> info;
public PersonResponse() {}
...getters / setters / toSting
PersonDetails:
public class PersonDetails implements Serializable{
private static final long serialVersionUID = 1294417456651475410L;
private int id;
private List<Person> person;
public PersonDetails(int version) {
super();
this.version = version;
}
...getters / setters / toSting
Person
public class Person implements Serializable{
private static final long serialVersionUID = 3290753964441709903L;
private String identifier;
private String role;
public Person(String identifier, String role) {
super();
this.identifier = identifier;
this.role = role;
}
...getters / setters / toSting
The problem isn't the JSON necessarily, it's that the JSON structure doesn't match your PersonResponse class. There's an info variable in PersonResponse that requires an array of what I assume to be persons, in the second example you're trying to push an object in there, which you can't. You have to either change your JSON, which you don't seem to want in this case, or the class you're trying to parse it to.
You need to restructure the info variable in PersonResponse to match the object you're trying to parse to it.
I build an google Calendar API, and i miss understand a point with my json files.
I succeed to create my java object with my json files but here the issue:
i have two classes :
public class User {
private String email;
private String firstname;
private String lastname;
Entity entity;
``
and my Entity
`` public class Entity {
private String name;
private String entityType;
private Entity rootEntity;``
here my json file :
for user
``[
{
"firstname": "Jean-Marc",
"lastname": "Chevereau",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"BFA",
"entityType":"secteur"
}
},
{
"firstname": "Florent",
"lastname": "Hamlin",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"IT",
"entityType":"secteur"
}
},
{
"firstname": "Benoit",
"lastname": "Micaud",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"EX",
"entityType":"offre",
"rootEntity":{
"name":"BFA"
}
}
}
]``
And a Entity json file
```[
{
"name": "BFA",
"entityType": "secteur",
"rootEntity": "",
},
{
"name": "EX",
"entityType": "Offre",
"rootEntity": "BFA",
}
}
]
But here the trouble. if in my User.json i write theEntity Name, i dont want to write entitytype and rootEntity, because if i write Entity Name is BFA, it will always be the same entitType and the rootEntity.
In others words, my json Entity will be always the same,and if i just put the name we know that refers to an entity object.
For instance, in this user.json file, I will just need to put
[
{
"firstname": "Jean-Marc",
"lastname": "Chevereau",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"BFA",
}
},
{
"firstname": "Florent",
"lastname": "Hamlin",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"IT",
}
},
{
"firstname": "Benoit",
"lastname": "Micaud",
"email": "xxxxxxx#xxxxx.com",
"entity": {
"name":"EX",
}
}
]
In Json-lib you have a JsonConfig to specify the allowed fields:
JsonConfig jsonConfig=new JsonConfig();
jsonConfig.registerPropertyExclusion(Entity.class,"rootEntity");
jsonConfig.registerPropertyExclusion(Entity.class,"entityType");
JSON json = JSONSerializer.toJSON(objectToWrite,jsonConfig);
I suppose com.fasterxml.jackson's #JsonIgnore annotation should help.
public class Entity {
private String name;
#JsonIgnore
private String entityType;
#JsonIgnore
private Entity rootEntity;
}
I'm currently trying to parse a JSON response with the following structure using Gson:
{
data {
"1": {
"name": "John Doe"
},
"2": {
"name": "John Doe"
},
...
}
My response class:
class Response {
Map<String, ModelObj> data;
}
and model class:
class ModelObj {
String name;
}
But what I can't figure out is how to simply map everything to a single List where the id is placed within the ModelObj without having them separate as key/value pairs in a Map. So ideally my response class would be:
class Response {
List<ModelObj> data;
}
and model class:
class ModelObj {
String id;
String name;
}
How would this be accomplished?
[
{
"id": 1,
"name": "John Doe"
},
{
"id": 2,
"name": "John Doe"
}
]
If your response is of above form then only you will get the list of model object and you will get Array of ModelObj
then use below code to convert to List
public <T> List<T> getObjectToList(String json, Class<T[]> ObjectArrayClass) {
return Arrays.asList(gson.fromJson(json, ObjectArrayClass));
}
List< ModelObj > arrayList = getObjectToList(jsonResponseString, ModelObj[].class);
I need to convert below json to java object of #RequestBody.
{
"entity": {
"id": 3,
"name": "james"
},
"conjunction": "OR",
"conditions": [
{
"operation": "equalTo",
"dataKey": "department",
"dataType": "string",
"value": "abc"
},
{
"operation": "notEqualTo",
"dataKey": "ID",
"dataType": "number",
"value": "100"
},
{
"operation": "notEqualTo",
"dataKey": "name",
"dataType": "strubg",
"value": "jack"
},
{
"operation": "between",
"dataKey": "END_DATE",
"dataType": "date",
"value1": "20180502",
"value2": "20180519"
}
]
}
The first three element in the array correspond to below java object.
public class ComparisonCondition extends Condition {
private String value;
}
The last element correspond below object.
public class BetweenCondition extends Condition {
private String value1;
private String value2;
}
They all inherit from below object.
public class Condition {
private String dataKey;
private String dataType;
private String operation;
}
The spring mvc method is below.
#RequestMapping(value = RequestAction.FILTER, method = RequestMethod.POST)
public List<Student> filter(
#RequestBody Filter<Student> filterConfig) {
return null;
}
The Filter object is below.
public class Filter<T> {
private String conjunction;
private T entity;
private List<Condition> conditions;
}
How can I map the json to java object successfully?
Currently it report "Could not read JSON: Unrecognized field "value" (class com.ssc.rest.entity.Condition), not marked as ignorable (3 known properties: "dataType", "dataKey", "operation"])
For your error, if the jackson parser don't know a field, it throws an exception.
You can avoid it by putting the annotation :
#JsonIgnore(ignoreUnknown=true)
on the target object.
For your mapping, I recommand to you to create an object corresponding to your json input, and then do manually your mapping to your target objects.
You are passing 4 variables in JSON for COndition
{
"operation": "equalTo",
"dataKey": "department",
"dataType": "string",
"value": "abc"
},
but your Java POJO has only 3 variables
public class Condition {
private String dataKey;
private String dataType;
private String operation;
}
just add value as well it will work fine.
Bottom line is : POJO class should have all the fields passed in JSON.
By the way your exception is telling same thing
Unrecognized field "value"
Edit 1:
I missed BetweenCondition and ComparisonCondition
You can define the Base Class in your case Condition with Sub Class property and hopefully it should work
#JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "javaclass")
#JsonSubTypes({
#Type(value = ComparisonCondition.class),
#Type(value = BetweenCondition.class)
})
public class Condition {
private String dataKey;
private String dataType;
private String operation;
}
I have a JSON response coming as shown below. I am trying to make a POJO for this so that I can serialize this JSON into my POJO.
{
"holder": [
{
"ids": [
{
"data": "abcdef1234",
"time": 1452720139465,
"days": 16813
},
{
"data": "abcdef12345678",
"time": 1452720139465,
"days": 16813
},
{
"data": "abcdef12345678901234",
"time": 1452720139465,
"days": 16813
}
],
"type": "HELLO"
}
]
}
And this is my POJO I was able to come up with but it doesn't look right.
public class TestResponse {
private List<Ids> holder;
private String type;
// getters and setters
public static class Ids {
private String data;
private long time;
private long days;
// getters and setters
}
}
My json is not getting serialized to my above POJO
go to this link www.jsonschema2pojo.org and past yout json and extract jar files and import in your project and do some changes link this.
$class TestResponse {
to
class TestResponse implement serializable{