flexjson.JSONException Don't know how to bind - java

My android application use flexjson library to deserialize json data string received from server via RESTfull webservice. But when deserialize i get error.
flexjson.JSONException: [ data.status ]: Don't know how to bind Clock_in into class wfa.com.tma.wfa.type.TimeClockStatus. You might need to use an ObjectFactory instead of a plain class.
this is my String
{
"data":
{
"todayShift":
{
"startTime":"1970-01-01T13:30:00Z",
"endTime":"1970-01-02T00:00:00Z",
"office":
{
"id":1,"name":"Location Test 1"
}
},
"currentTime":"2017-10-12T07:47:11Z",
"status":"Clock_in",
"latestTime":"2017-10-12T07:46:13Z",
"latestOffice":{"id":1,"name":"Location Test 1"}},
"meta":{"type":"TimeClockDto"}
}
the DTO of this String
public class TimeClockDto implements Serializable
{
private static final long serialVersionUID = 1L;
private TodayShiftDto todayShift;
private String currentTime;
private TimeClockStatus status;
private String latestTime;
private BaseLocationDto latestOffice;
public TimeClockDto(TodayShiftDto todayShift, String currentTime,
TimeClockStatus status, String latestClockInTime,
BaseLocationDto latestOffice)
{
this.todayShift = todayShift;
this.currentTime = currentTime;
this.status = status;
this.latestTime = latestClockInTime;
this.latestOffice = latestOffice;
}
//getter, setter
}
`and the deserialize code
and the enum class
public enum TimeClockStatus
{
Clock_in, Clock_out;
}

I have solve this problem by using EnumObjectFactory
TimeClockDto result = new JSONDeserializer<TimeClockDto>
.use("data", TimeClockDto.class)
.use("data.todayShift", TodayShiftDto.class)
.use("data.status", new EnumObjectFactory())
.use("data.latestOffice", BaseLocationDto.class)
.deserialize(param.getResult(),TimeClockDto.class);

Related

Read json file from POST in java

How can I unmarhsaller json file like this?
{
"packageId": "11",
"jsScript": "var divideFn = function(a,b) { return a/b} ",
"functionName": "divideFn",
"tests": [
{
"testName": "test1",
"expectedResult": "2.0",
"params": [
2,
1
]
}
]
}
I have a class that works well with packageId, jsScrript, functionName, but not with the tests
public class Data {
private final int packageId;
private final String jsScript;
private final String functionName;
private final List<Tests> tests;
#JsonCreator
public Data(#JsonProperty("packageId") String packageId,
#JsonProperty("jsScript") String jsScript,
#JsonProperty("functionName") String functionName,
#JsonProperty("tests") List<Tests> tests) {
this.packageId = Integer.parseInt(packageId);
this.jsScript= jsScript;
this.functionName = functionName;
this.tests = tests;
}
}
public class Tests{
public final String testName;
public final int expectedResult;
#JsonCreator
public Tests(#JsonProperty("testName") String testName,
#JsonProperty("expectedResult") String expectedResult){
this.testName= testName;
this.expectedResult = Integer.parseInt(expectedResult);
}
}
What should I change in classes to make it work well?
I also tried to read tests like String, but it didn't help
It seems that you have encountered some problems for deserializing the JSON array tests to objects. There are several methods to solve this.
Method 1
Add #JsonIgnoreProperties(ignoreUnknown = true) on your class Tests to prevent your code from the exception of Unrecognized field "params".
Method 2
Deserialize JSON array tests to List<JsonNode> if it is not important and you won't further parse it in the future.
Method 3
Use follwing class for mapping JSON array tests to List<Test>.
class Test {
private String testName;
private Float expectedResult;
private List<Integer> params;
//general getters ans setters
}
BTW, I don't think you need to use #JsonCreator for deserialization.

How to get an arrayJSON in webService Rest?

I am developing a WEb Service Rest in java, netbeans.
This is the JSON I want to receive:
{
"ticket":"2132158645161654561651616",
"avaliacoes":[
{
"id":1,
"nome":"Atendimento",
"nota":5,
"observacoes":"testeTEste"
},
{
"id":2,
"nome":"Atendimento",
"nota":5,
"observacoes":"testeTEste"
}
]
}
Reception Class
#PUT
#Consumes(MediaType.APPLICATION_JSON)
#Path("venda/enviardados")
public String postVenda(#QueryParam("key") String key, #QueryParam("serial") String serial, VendaAvaliacao va) {
...
}
Entity Classes
public class VendaAvaliacao {
private int id;
private String ticket;
//private List<VendaAvaliacaoInner> avaliacoes = new ArrayList<>(); //I've tried it too
private VendaAvaliacaoInner[] teste;
}
public class VendaAvaliacaoInner {
private int id;
private String nome;
private int nota;
private String observacao;
}
The ticket is received and populated, but array = null.
I've read other similar topics but they did not help .... how can I do?
https://pt.stackoverflow.com/questions/6046/convers%C3%A3o-de-string-json-para-objeto-java?rq=1
https://pt.stackoverflow.com/questions/159725/receber-valor-de-array-json-para-string-java
https://pt.stackoverflow.com/questions/290759/como-obter-objetos-de-um-array-de-json-usando-jsonarray-no-java
Maybe the service REST you are consuming don't populate the data in the array.
As an advice i would work with List<T> rather than T[]
Also i see that you are mapping 3 properties in you object but the id property don't exist in raw JSON isn't it ?

Java object not populated from json request for inner class

Have searched in different sites but couldn't find correct answer, hence posting this request though it could possible duplicates.sorry for that.
I am sending the below json request to my back-end service and converting to java object for processing. I can see the request body passed to my service but when i convert from json to java object , values are not populating
{
"data":{
"username":"martin",
"customerId":1234567890,
"firstName":"john",
"lastName":"smith",
"password":"p#ssrr0rd##12",
"email":"john.smith#gmail.com",
"contactNumber":"0342323443",
"department":"sports",
"location":"texas",
"status":"unlocked",
"OrderConfigs":[
{
"vpnId":"N4234554R",
"serviceId":"connectNow",
"serviceType":"WRLIP",
"ipAddress":"10.101.10.3",
"fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
"timeout":1800,
"mapId":"test_map"
}
]
}
}
My Parser class have something like,
JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
ObjectMapper mapper = new ObjectMapper();
final String jsonData = requestJSON.toString();
OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
// I can see value coming from front-end but not populating in the mappedObject
My OrderDTO.java
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
public class OrderDTO {
private String username;
private long customerId;
private String source;
private String firstName;
private String lastName;
private String email;
private String contactNumber;
private String password;
private String department;
private String location;
private String status;
private List<OrderConfig> OrderConfigs;
#JsonInclude(value = Include.NON_NULL)
public class OrderConfig {
private String vpnId;
private String serviceId;
private String serviceType;
private String ipAddress;
private String mapId;
private String[] fRoutes;
private Map<String, Object> attributes;
private SubConfig subConfig;
private String routeFlag;
getter/setters
.....
}
all setter/getter
}
Not sure what I'm missing here. Is this right way to do?
If your are trying to use inner class, correct way to use is to declare it static for Jackson to work with inner classes.
For reference check this
code changes made are
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
static class OrderConfig {
Make sure that your json tag names match with variable names of java object
Ex : "fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
private String[] fRoutes;
OrderConfigs fields will not be initialized, just modify your bean as
#JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;
// setter and getter as setOrderConfigs / getOrderConfigs
See my answer here. (same issue)

Retrofit/Android - dynamic response support

I'm having trouble with mapping resulting json data to pojo class with Retrofit. I need to determine Firebase topics by token. This can be eaisly done with Google's json api, as described here: https://developers.google.com/instance-id/reference/server#get_information_about_app_instances
In my case, server response is simlar to this:
{
"applicationVersion": "36",
"connectDate": "2018-02-04",
"attestStatus": "ROOTED",
"application": "<my application id>",
"scope": "*",
"authorizedEntity": "205414012839",
"rel": {
"topics": {
"topic1": {
"addDate": "2018-02-04"
},
"topic2": {
"addDate": "2018-01-31"
}
}
},
"connectionType": "WIFI",
"appSigner": "<hash>",
"platform": "ANDROID"
}
The problem is basically rel and topics structure, because topics is dynamic and field list can by anything and it's unknown. So I can't generate simple POJO to get it mapped by Retrfofit automatically.
Can I force Retrofit to treat topics as single String field, I will able to parse it later to retrieve topics list? Or is there any other soulution?
Any ideas?
If you use gson, you can define rel as a JsonElement. If you use moshi, you can define it as a Map.
for gson:
public class Response{
private String applicationVersion;
private String connectDate;
private String attestStatus;
private String application;
private String scope;
private String authorizedEntity;
private String connectionType;
private String appSigner;
private String platform;
private JsonElement rel;
}
for moshi:
public class Response{
private String applicationVersion;
private String connectDate;
private String attestStatus;
private String application;
private String scope;
private String authorizedEntity;
private String connectionType;
private String appSigner;
private String platform;
private Map<String, Map<String, Map<String, String>>> rel;
}

Spring JPA - How JSON should be formatted and how to call with RestTemplate

I've created a service with this specification:
#RequestMapping(value = "initCustomer", method = RequestMethod.POST)
public ResponseEntity<Long> create(#RequestBody CustomerForm customerForm) {
The element CustomerForm have this structure (i omit every getter/setter method):
#XmlRootElement(name = "customer")
public static class CustomerForm {
private String name;
private String hostname;
private List<ProbeMonitor> monitors;
#XmlElement(name = "monitor")
public List<ProbeMonitor> getMonitors() {
return monitors;
}
}
The class ProbeMonitor is an #Entity with an #EmbeddedId (because this classe have more than one field in the primary key).
public class ProbeMonitor implements Serializable {
private static final long serialVersionUID = 1L;
private ProbeMonitorId id;
private Integer active;
private Date inserted;
private Date updated;
#EmbeddedId
public ProbeMonitorId getId() {
return id;
}
}
And finally, ProbeMonitorId:
#Embeddable
public class ProbeMonitorId implements Serializable {
private static final long serialVersionUID = 1L;
private String customer;
private String name;
private String type;
}
Now i should make a request to this service (using RestTemplate), but first i'm trying to use a simple REST client where i send JSON (to check that all works).
I'm sending JSON in this format, but i get "Unrecognized field "id""
{
"name": "test_name",
"hostname": "test_hosT",
"monitors": [
{ "id": {"customer": "custom"},
"active": "1"
}
]
}
I've tried to remove the "id" fields in JSON request and WebService will be invoked correctly.
How "monitors" should be formatted?
And... (this is the second question) how i should create the RestTemplate to call this?
I think to have found the problems:
1 - private ProbeMonitorId id; was not declared in JSON scope:
#EmbeddedId
**#XmlElement**
#**JsonProperty**
public ProbeMonitorId getId() {
return id;
}
2 - Inserted and updated was not declared to be ignored
#Basic
#Column(name = "Dt_Insert")
#JsonIgnore
public Date getInserted() {
return inserted;
}
3 - Correct JSON sent:
{
"name": "test_name",
"hostname": "test_hosT",
"monitors": [{
"id": {"customer": "cst", "name": "aname", "type": "atype"},
"active": "1"
}
]

Categories