Create complex JSON from a java object - java

These are my classes.
Class TypeC {
int var1;
HashMap<String,String>var2;
ArrayList<TypeC> var3;
}
Class TypeB {
TypeC var1;
}
Class TypeA {
Long var1;
TypeB var2;
}
I want to create object of TypeC and then convert it into a corresponding JSON object (complex JSON).
I tried the following but it doesnt work.
TypeC obj = new TypeC();
JSONObject TypeCJSON=new JSONObject(obj);

A full example of data binding using 'com.fasterxml.jackson.databind.ObjectMapper' :
package spring.exos;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args){
final Computer computer = new Computer();
computer.setBrand("Toshiba");
computer.setModel("TSB I7-SSD");
computer.setSpecs(new Specs(new Integer(256), new Integer(8), new Double(2.4)));
final ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writeValueAsString(computer));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public static class Computer{
private String brand;
private String model;
private Specs specs;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Specs getSpecs() {
return specs;
}
public void setSpecs(Specs specs) {
this.specs = specs;
}
}
public static class Specs {
private Integer hdd;
private Integer memory;
private Double cpu;
public Specs(Integer hdd, Integer memory, Double cpu) {
super();
this.hdd = hdd;
this.memory = memory;
this.cpu = cpu;
}
public Integer getHdd() {
return hdd;
}
public void setHdd(Integer hdd) {
this.hdd = hdd;
}
public Integer getMemory() {
return this.memory;
}
public void setMemory(Integer memory) {
this.memory = memory;
}
public Double getCpu() {
return cpu;
}
public void setCpu(Double cpu) {
this.cpu = cpu;
}
}
}
The output is :
{"brand":"Toshiba","model":"TSB I7-SSD","specs":{"hdd":256,"memory":8,"cpu":2.4}}
You need to have a dependency to:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>

if you are willing to use another library, using Gson https://github.com/google/gson you just need to do this:
String json = new Gson().toJson(object);

Related

Parse Json with Gson in EnumClass

I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks

Consuming a third party RESTful API passing a parameter

I need to consume a third party RESTful API. This is my controller class:
#Controller
public class BrokerController {
#RequestMapping(value = "/broker", method = RequestMethod.POST)
public #ResponseBody MyPojo brokers(#RequestBody BrokerRequest brokerRequest){
RestTemplate restTemplate = new RestTemplate();
final String uri = "http://www.nepalipaisa.com/Modules/MarketMovers/Services/MarketMoversServices.asmx/GetTopBrokers";
MyPojo myPojo = restTemplate.postForObject(uri,brokerRequest,MyPojo.class);
return myPojo;
}
}
Edited:- My pojo class:
public class MyPojo {
private String __type;
private Integer RowTotal;
private Integer StockID;
private Object CodedCompany;
private Object ClosingPrice;
private Integer Amount;
private Integer PreviousClosing;
private Integer DifferenceRS;
private Object Symbol;
private Integer Price;
private Integer Diff;
private Integer PercentageDiff;
private Object Volume;
private Integer TotalTurnOverAmount;
private String FirmName;
private Integer BrokerID;
private String BrokerCode;
private Integer TotalTransactions;
private Object Traded;
private Object MaxPrice;
private Object MinPrice;
private Object OpeningPrice;
private Object TotalShare;
private Integer NoOfTransaction;
private Integer Purchase;
private Integer Sales;
private Integer Matching;
public String get__type() {
return __type;
}
public void set__type(String __type) {
this.__type = __type;
}
public Integer getRowTotal() {
return RowTotal;
}
public void setRowTotal(Integer rowTotal) {
this.RowTotal = rowTotal;
}
public Integer getStockID() {
return StockID;
}
public void setStockID(Integer stockID) {
this.StockID = stockID;
}
public Object getCodedCompany() {
return CodedCompany;
}
public void setCodedCompany(Object codedCompany) {
this.CodedCompany = codedCompany;
}
public Object getClosingPrice() {
return ClosingPrice;
}
public void setClosingPrice(Object closingPrice) {
this.ClosingPrice = closingPrice;
}
public Integer getAmount() {
return Amount;
}
public void setAmount(Integer amount) {
this.Amount = amount;
}
public Integer getPreviousClosing() {
return PreviousClosing;
}
public void setPreviousClosing(Integer previousClosing) {
this.PreviousClosing = previousClosing;
}
public Integer getDifferenceRS() {
return DifferenceRS;
}
public void setDifferenceRS(Integer differenceRS) {
this.DifferenceRS = differenceRS;
}
public Object getSymbol() {
return Symbol;
}
public void setSymbol(Object symbol) {
this.Symbol = symbol;
}
public Integer getPrice() {
return Price;
}
public void setPrice(Integer price) {
this.Price = price;
}
public Integer getDiff() {
return Diff;
}
public void setDiff(Integer diff) {
this.Diff = diff;
}
public Integer getPercentageDiff() {
return PercentageDiff;
}
public void setPercentageDiff(Integer percentageDiff) {
this.PercentageDiff = percentageDiff;
}
public Object getVolume() {
return Volume;
}
public void setVolume(Object volume) {
this.Volume = volume;
}
public Integer getTotalTurnOverAmount() {
return TotalTurnOverAmount;
}
public void setTotalTurnOverAmount(Integer totalTurnOverAmount) {
this.TotalTurnOverAmount = totalTurnOverAmount;
}
public String getFirmName() {
return FirmName;
}
public void setFirmName(String firmName) {
this.FirmName = firmName;
}
public Integer getBrokerID() {
return BrokerID;
}
public void setBrokerID(Integer brokerID) {
this.BrokerID = brokerID;
}
public String getBrokerCode() {
return BrokerCode;
}
public void setBrokerCode(String brokerCode) {
this.BrokerCode = brokerCode;
}
public Integer getTotalTransactions() {
return TotalTransactions;
}
public void setTotalTransactions(Integer totalTransactions) {
this.TotalTransactions = totalTransactions;
}
public Object getTraded() {
return Traded;
}
public void setTraded(Object traded) {
this.Traded = traded;
}
public Object getMaxPrice() {
return MaxPrice;
}
public void setMaxPrice(Object maxPrice) {
this.MaxPrice = maxPrice;
}
public Object getMinPrice() {
return MinPrice;
}
public void setMinPrice(Object minPrice) {
this.MinPrice = minPrice;
}
public Object getOpeningPrice() {
return OpeningPrice;
}
public void setOpeningPrice(Object openingPrice) {
this.OpeningPrice = openingPrice;
}
public Object getTotalShare() {
return TotalShare;
}
public void setTotalShare(Object totalShare) {
this.TotalShare = totalShare;
}
public Integer getNoOfTransaction() {
return NoOfTransaction;
}
public void setNoOfTransaction(Integer noOfTransaction) {
this.NoOfTransaction = noOfTransaction;
}
public Integer getPurchase() {
return Purchase;
}
public void setPurchase(Integer purchase) {
this.Purchase = purchase;
}
public Integer getSales() {
return Sales;
}
public void setSales(Integer sales) {
this.Sales = sales;
}
public Integer getMatching() {
return Matching;
}
public void setMatching(Integer matching) {
this.Matching = matching;
}
}
The JSON iI need to consume, i.e the exact result given below:
{
"d": [
{
"__type": "SageFrame.MarketMovers.MarketInfo",
"RowTotal": 0,
"StockID": 0,
"CodedCompany": null,
"ClosingPrice": null,
"Amount": 0,
"PreviousClosing": 0,
"DifferenceRS": 0,
"Symbol": null,
"Price": 0,
"Diff": 0,
"PercentageDiff": 0,
"Volume": null,
"TotalTurnOverAmount": 109969058,
"FirmName": "Vision Securities Pvt. Ltd.",
"BrokerID": 0,
"BrokerCode": "34",
"TotalTransactions": 0,
"Traded": null,
"MaxPrice": null,
"MinPrice": null,
"OpeningPrice": null,
"TotalShare": null,
"NoOfTransaction": 0,
"Purchase": 70691939,
"Sales": 39277119,
"Matching": 6381555
},
{
"__type": "SageFrame.MarketMovers.MarketInfo",
"RowTotal": 0,
"StockID": 0,
"CodedCompany": null,
"ClosingPrice": null,
"Amount": 0,
"PreviousClosing": 0,
"DifferenceRS": 0,
"Symbol": null,
"Price": 0,
"Diff": 0,
"PercentageDiff": 0,
"Volume": null,
"TotalTurnOverAmount": 104830489,
"FirmName": "Online Securities Pvt. Ltd.",
"BrokerID": 0,
"BrokerCode": "49",
"TotalTransactions": 0,
"Traded": null,
"MaxPrice": null,
"MinPrice": null,
"OpeningPrice": null,
"TotalShare": null,
"NoOfTransaction": 0,
"Purchase": 51927902,
"Sales": 52902587,
"Matching": 3049044
}
]
}
Currently when I send a POST request with two parameters
{
"offset":"1",
"limit":"2000"
}
I can get the result given above. Now I need to return the same result but through my own controller. The above controller returns MyPojo class with null value on every properties.
You can always try to put the results from the third party API into a Map.
Map results = restTemplate.postForObject(uri,brokerRequest, Map.class);
Or you can create a new pojo just for that third part API.
ThirdPartyPojo results = restTemplate.postForObject(uri,brokerRequest, ThirdPartyPojo.class);
Right now the issue is that your pojo MyPojo is not compatible with the response of 3rd party API.
Your pojo should be something like following.
-----------------------------------com.example.D.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
public class D {
private String type;
private Integer rowTotal;
private Integer stockID;
private Object codedCompany;
private Object closingPrice;
private Integer amount;
private Integer previousClosing;
private Integer differenceRS;
private Object symbol;
private Integer price;
private Integer diff;
private Integer percentageDiff;
private Object volume;
private Integer totalTurnOverAmount;
private String firmName;
private Integer brokerID;
private String brokerCode;
private Integer totalTransactions;
private Object traded;
private Object maxPrice;
private Object minPrice;
private Object openingPrice;
private Object totalShare;
private Integer noOfTransaction;
private Integer purchase;
private Integer sales;
private Integer matching;
// Getter .. Setter//
}
-----------------------------------com.example.MyPojo.java-----------------------------------
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
public class Example {
#JsonProperty("d")
private List<D> d = null;
// Getter ... Setter
}
Or simply you can use Map.
This can be accomplished easily not even requiring you to provide custom mappings or whatever like that and guarantee that your controller wil provide the same response (not the same headers, though):
#RestController
final class Controller {
// Both RestTemplate and URI instances can be cached
private static final RestTemplate restTemplate = new RestTemplate();
private static final URI testUri = URI.create("http://www.nepalipaisa.com/Modules/MarketMovers/Services/MarketMoversServices.asmx/GetTopBrokers");
// I'm using GET just to simplify the testing using a web browser
#RequestMapping(method = GET, value = "/")
public void post(final ServletResponse response)
throws IOException {
// Create a POST request entity
final RequestEntity<?> requestEntity = new RequestEntity<>(getRequest(0, 10), POST, testUri);
// And send the request to the remote server
final ResponseEntity<Resource> responseEntity = restTemplate.exchange(requestEntity, Resource.class);
// Now just copy the response input stream to the output stream of this controller
try ( final InputStream inputStream = responseEntity.getBody().getInputStream() ) {
// Or provide HttpServletResponse via the controller method to be able to configure the response more accurately
StreamUtils.copy(inputStream, response.getOutputStream());
}
}
private static Object getRequest(final long offset, final long limit) {
final Map<String, Object> request = new HashMap<>();
request.put("offset", offset);
request.put("limit", limit);
return request;
}
}
The remote server can respond with a non-successful response code, so you can also have a custom controller advice to handle RestTemplate exceptions:
#ControllerAdvice
final class ExceptionControllerAdvice {
#ExceptionHandler(HttpServerErrorException.class)
#ResponseBody
public ResponseEntity<?> handleHttpServerErrorException(final HttpServerErrorException ex) {
return new ResponseEntity<Object>("Bad gateway: " + ex.getMessage(), BAD_GATEWAY);
}
}

Java spring rest service does not cast parameter

I'm create REST api with springFramework. Create products from post api, but rest method does not cast the parameters with TitleCase parameter name.
My Product model:
public class Product extends BaseModel {
private String title;
private String shortDescription;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
}
My Product REST Api:
#PostMapping(value = "/product", consumes = {MediaType.APPLICATION_JSON_VALUE})
public ApiResponse Insert(#RequestBody Product model){
ApiResponse response = new ApiResponse();
try{
response.setData(_service.Insert(model));
response.setSuccess(true);
} catch (Exception ex){
response = _service.HandleException(ex);
}
return response;
}
Worked Request Object:
{
"title" : "TEST",
"shortDescription" : "SD",
"longDescription" : "LD"
}
Not Worked Request Object:
{
"Title" : "TEST",
"ShortDescription" : "SD",
"LongDescription" : "LD"
}
I want both options to work. I'm new to Java, so I did not know how to get around to it, so I wanted to ask.
UPDATED
Jackson Config File
#Configuration
#EnableWebMvc
public class JacksonConfiguration {
#Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
return mapper;
}
}
Thanks.
This works fine:
package com.example;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class Test {
private ObjectMapper mapper;
public static class A{
private int test;
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
}
#Before
public void setUp(){
mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
}
#Test
public void deserialise() throws Exception {
String json = "{\"test\":\"2\"}";
assertThat(mapper.readValue(json, A.class).getTest(), is(2));
}
#Test
public void deserialiseIgnoringCase() throws Exception {
String json = "{\"Test\":\"2\"}";
assertThat(mapper.readValue(json, A.class).getTest(), is(2));
}
}
Product model does not seem to have longDescription field. That might be the reason why deserialisation will fail (as there is no #JsonIgnore) on Product class. Below snippet works fine:
class Product {
private String title;
private String shortDescription;
private String longDescription;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
}
public static void main(String[] args) throws Exception{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
Product product = mapper.readValue("{\"Title\" : \"TEST\",\"ShortDescription\" : \"SD\",\"LongDescription\" : \"LD\"}", Product.class);
System.out.println(product.getShortDescription());
}
It will throw an Exception if you comment out longDescription.

Get jersey/jackson json into several classes

I have this json response from a server.
{"session_key":"thekey","expires_in":300,"environment":"exttest","country":"SE","private_feed":{"hostname":"priv.api.test.nordnet.se","port":443,"encrypted":true},"public_feed":{"hostname":"pub.api.test.nordnet.se","port":443,"encrypted":true}}
The top level info is parsed fine into the below class. But how do I populate the list of server info?
The code
Response response = baseResource.path("login").queryParam("service", "NEXTAPI")
.queryParam("auth", authParam).request(responseType).post(null);
System.out.println(response);
SessionInfo ses = response.readEntity(SessionInfo.class);
public class SessionInfo {
public String session_key;
public String environment;
public int expires_in;
public String country;
List<ServerInfo> serverInfo = new ArrayList<ServerInfo>();
}
public class ServerInfo {
public String hostname;
public int port;
public boolean encrypted;
}
This works, but I would hope there is a way to convert it in one step since there might be more nested levels in other responses.
ObjectMapper mapper = new ObjectMapper();
ObjectNode json = response.readEntity(ObjectNode.class);
SessionInfo ses = mapper.treeToValue(json, SessionInfo.class);
ServerInfo s1 = mapper.treeToValue(json.get("private_feed"), ServerInfo.class);
ServerInfo s2 = mapper.treeToValue(json.get("public_feed"), ServerInfo.class);
ses.serverInfo.add(s1);
ses.serverInfo.add(s2);
I tried using Jackson, and was able to build the JSON object in one liner. Probably what you are looking for.
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JackSontest {
public static void main(String[] args){
String jstr = "{\"session_key\":\"thekey\",\"expires_in\":300,\"environment\":\"exttest\",\"country\":\"SE\",\"private_feed\":{\"hostname\":\"priv.api.test.nordnet.se\",\"port\":443,\"encrypted\":true},\"public_feed\":{\"hostname\":\"pub.api.test.nordnet.se\",\"port\":443,\"encrypted\":true}}";
System.out.println("Calling jsonToObject...");
ObjectMapper objectMapper = new ObjectMapper();
try {
SessionInfo info = objectMapper.readValue(jstr, SessionInfo.class);
System.out.println("Session_key:- " + info.getSession_key());
System.out.println("Expires_in:- " + info.getExpires_in());
System.out.println("Environment:- " + info.getEnvironment());
System.out.println("Private Feed:- " + info.getPrivate_feed().getHostname());
System.out.println("Public Feed:- " + info.getPublic_feed().getHostname());
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SessionInfo {
private String session_key;
private String environment;
private int expires_in;
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
private String country;
private Feed private_feed;
public Feed getPrivate_feed() {
return private_feed;
}
#JsonProperty("private_feed")
public void setPrivate_feed(Feed private_feed) {
this.private_feed = private_feed;
}
private Feed public_feed;
public Feed getPublic_feed() {
return public_feed;
}
#JsonProperty("public_feed")
public void setPublic_feed(Feed public_feed) {
this.public_feed = private_feed;
}
}
class Feed {
private String hostname;
private int port;
private boolean encrypted;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isEncrypted() {
return encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
}
Output:
Calling jsonToObject...
Session_key:- thekey
Expires_in:- 300
Environment:- exttest
Private Feed:- priv.api.test.nordnet.se
Public Feed:- priv.api.test.nordnet.se
have you tried Gson:
public class Employee
{
private Integer id;
private String firstName;
private String lastName;
private List<String> roles;
private Department department; //Department reference
//Other setters and getters
}
class DepartmentInstanceCreator implements InstanceCreator<Department> {
public Department createInstance(Type type)
{
return new Department("None");
}
}
//Now <strong>use the above InstanceCreator</strong> as below
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());
Gson gson = gsonBuilder.create();
System.out.println(
gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}",
Employee.class));
Output:
Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]
source

JsonMappingException during Json unmarshal in Spring

This is my POJO class:
public class OrdineIngressi {
private Integer spettacolo;
private Integer settore;
private Integer pv;
private List<OrdineIngresso> ingressi=new ArrayList<OrdineIngresso>();
public OrdineIngressi(Integer spettacolo, Integer settore, Integer pv,
List<OrdineIngresso> ingressi) {
super();
this.spettacolo = spettacolo;
this.settore = settore;
this.pv = pv;
this.ingressi = ingressi;
}
public OrdineIngressi() {
super();
}
public Integer getSpettacolo() {
return spettacolo;
}
public void setSpettacolo(Integer spettacolo) {
this.spettacolo = spettacolo;
}
public Integer getSettore() {
return settore;
}
public void setSettore(Integer settore) {
this.settore = settore;
}
public Integer getPv() {
return pv;
}
public void setPv(Integer pv) {
this.pv = pv;
}
public List<OrdineIngresso> getIngressi() {
return ingressi;
}
public void setIngressi(List<OrdineIngresso> ingressi) {
this.ingressi = ingressi;
}
public class OrdineIngresso {
private Integer tipoingresso;
private Integer abbonamento;
private int numero;
private Integer[] posti;
public OrdineIngresso() {
super();
}
public OrdineIngresso(Integer tipoingresso, Integer abbonamento,
int numero, Integer[] posti) {
super();
this.tipoingresso = tipoingresso;
this.abbonamento = abbonamento;
this.numero = numero;
this.posti = posti;
}
public Integer getTipoingresso() {
return tipoingresso;
}
public void setTipoingresso(Integer tipoingresso) {
this.tipoingresso = tipoingresso;
}
public Integer getAbbonamento() {
return abbonamento;
}
public void setAbbonamento(Integer abbonamento) {
this.abbonamento = abbonamento;
}
public Integer[] getPosti() {
return posti;
}
public void setPosti(Integer[] posti) {
this.posti = posti;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
}
}
This is the ajax input:
{"spettacolo":1,"settore":1,"pv":1,"ingressi":[{"tipoingresso":1,"abbonamento":null,"numero":1,"posti":[]}]}
When the Controller tries to unmarshal a json input I got this:
nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.bean.OrdineIngressi$OrdineIngresso]: can not instantiate from JSON object (need to add/enable type information?)
Why? There is a default constructor!
You're almost there, you just need to make your inner class static:
...
public static class OrdineIngresso {
private Integer tipoingresso;
...
}
IIRC it has to do with the fact that a non-args inner class constructor really isn't non-args and thus jackson doesn't have a general manner for instantiating these non-static inner classes.
Cheers,

Categories

Resources