how to store xml data in to arraylist java - java

I have an xml file with data (not complete xml file)
<header>
<ParameterContext>
<Parameter>
<Name>FILEID<Name>
<Value>1001445<Value>
</Parameter>
<Identifier>Id</Identifier>
</ParameterContext>
<ParameterContext>
<Parameter>
<Name>product</Name>
<Value>ECT</ns0:Value>
</Parameter>
<Identifier>ProductName</Identifier>
</ParameterContext>
</header>
please help me to store this xml data(data of parametercontext elements) in to arraylist.
Sorry for not posting this earlier.
I have 2 classes object and load
public class object{
private ArrayList<ParameterContext> parameterCtx = new ArrayList<ParameterContext>();
public ArrayList<ParameterContext> getParameterCtx() {
return parameterCtx;
}
public void setParameterCtx(ParameterContext parameterCtx) {
this.parameterCtx.add(parameterCtx) ;
}
public Parameter searchParameter(String name, String identifier, ArrayList<ParameterContext> al) {
for(int i = 0; i < al.size(); i++) {
if(al.get(i).getIdentifier().equalsIgnoreCase(identifier)) {
for(int j = 0; j < al.get(i).getParameter().size(); j++) {
if(al.get(i).getParameter().get(j).getName().equalsIgnoreCase(name) ) {
return al.get(i).getParameter().get(j);
}
}
}
}
return null ;
}
}
and
public class load{
#XmlElement(name = "ParameterContext")
protected List<load.ParameterContext> parameterContext;
public List<load.ParameterContext> getParameterContext() {
if (parameterContext == null) {
parameterContext = new ArrayList<load.ParameterContext>();
}
return this.parameterContext;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"parameter",
"identifier"
})
public static class ParameterContext {
#XmlElement(name = "Parameter", required = true)
protected List<load.ParameterContext.Parameter> parameter;
#XmlElement(name = "Identifier", required = true)
protected String identifier;
public List<load.ParameterContext.Parameter> getParameter() {
if (parameter == null) {
parameter = new ArrayList<load.ParameterContext.Parameter>();
}
return this.parameter;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String value) {
this.identifier = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"value"
})
public static class Parameter {
#XmlElement(name = "Name", required = true)
protected String name;
#XmlElement(name = "Value", required = true)
protected String value;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
when i use object.searchparameter("FIELD","ID",object.getParameterCtx()).getValue());
NULLPOINTEREXCEPTION is coming.(getparameterCtx is not initialized).Before this line I need to initialize it right.How to Initialize?

using JAXB, create a class that mimics the XML
#XmlRootElement(name="header")
public class XMLBean {
public List<ParameterContext> pc;
public XMLBean() {
}
public List<ParameterContext> getPc() {
return pc;
}
public void setPc(List<ParameterContext> pc) {
this.pc = pc;
}
}
public class ParameterContext {
public Parameter parameter;
public String identifier;
public ParameterContext() {
}
public Parameter getParameter() {
return pc;
}
public void setParameter(Parameter parameter) {
this.param = param;
}
public String getIdentifier() {
return identifer;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}
public class Parameter {
public String name;
public String value;
public Parameter() {
}
public void setName(String name) {
this.name = name;
}
public void getName() {
return name;
}
public void setValue(String value) {
this.value = value;
}
public void getValue(String value) {
return value;
}
}
public static void main(String[] args) {
InputStream is = YOURXML
JAXBContext jaxb = JAXBContext.newInstace(XMLBean.class);
Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller();
XMLBean xml = (XMLBean) jaxbUnmarshaller.unmarshal(is);
System.out.println(xml.getParameterContext().get(0).getParam().getName());
System.out.println(xml.getParameterContext().get(0).getParam().getValue());
}
something like that

If the xml elements are same and repetitive Create an object with the attributes as the elements with getter/setters. Parse the xml data and store the value in the object.

Related

Jackson XML - Can't deserialize Boolean

I'm trying to parse XML content with Jackson but I have some difficulties with Boolean value.
This is a part of my XML content :
<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body xmlns:ns1="http://somecontent">
<wsResponse xmlns="http://somecontent">
<responseType>SUCCESS</responseType>
<response>
<successfullResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="InterchangeSearchResponse">
<totalResult>1</totalResult>
<returnedResults>1</returnedResults>
<pageIndex>1</pageIndex>
<interchanges>
<interchange>
<depositId>somecontent</depositId>
<interchangeId>somecontent</interchangeId>
<depositDate>2021-03-26T11:45:05.000+01:00</depositDate>
<depositSubject>dépôt WS</depositSubject>
<numADS>number</numADS>
<adsDate>2021-03-26T11:45:05.000+01:00</adsDate>
<alias>contentAsString</alias>
<version xsi:nil="true"/>
<isTest>false</isTest>
<deposantAccount>
<name>someString</name>
</deposantAccount>
<teleProcedure>someString</teleProcedure>
<statesHistory>
This is my XML structure as class :
#JacksonXmlProperty(localName = "Body")
private Body body;
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
}
#JacksonXmlRootElement
public class Body {
#JacksonXmlProperty(localName = "Fault")
private Fault fault;
private WsResponse wsResponse;
public Fault getFault() {
return fault;
}
public void setFault(Fault fault) {
this.fault = fault;
}
public WsResponse getWsResponse() {
return wsResponse;
}
public void setWsResponse(WsResponse wsResponse) {
this.wsResponse = wsResponse;
}
}
#JacksonXmlRootElement(localName = "wsResponse")
public class WsResponse {
private String responseType;
private Response response;
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
#JacksonXmlRootElement
public class Response {
private SuccessfulResponse successfullResponse;
private ErrorResponse errorResponse;
public SuccessfulResponse getSuccessfullResponse() {
return successfullResponse;
}
public void setSuccessfullResponse(SuccessfulResponse successfullResponse) {
this.successfullResponse = successfullResponse;
}
public ErrorResponse getErrorResponse() {
return errorResponse;
}
public void setErrorResponse(ErrorResponse errorResponse) {
this.errorResponse = errorResponse;
}
}
#JacksonXmlRootElement
public class SuccessfulResponse {
/**
* Response when add document success
*/
private String depositId;
/**
* Response when get interchanges by deposit id success
*/
private String type;
private Integer totalResult;
private Integer returnedResults;
private Integer pageIndex;
private Interchanges interchanges;
/**
* Response when get declaration details success
*/
private DeclarationTdfc declarationTdfc;
public SuccessfulResponse() {}
public SuccessfulResponse(String depositId) {
this.depositId = depositId;
}
public SuccessfulResponse(String type, Integer totalResult, Integer returnedResults, Integer pageIndex, Interchanges interchanges) {
this.type = type;
this.totalResult = totalResult;
this.returnedResults = returnedResults;
this.pageIndex = pageIndex;
this.interchanges = interchanges;
}
public SuccessfulResponse(DeclarationTdfc declarationTdfc) {
this.declarationTdfc = declarationTdfc;
}
public SuccessfulResponse(String depositId, String type, Integer totalResult, Integer returnedResults,
Integer pageIndex, Interchanges interchanges, DeclarationTdfc declarationTdfc) {
super();
this.depositId = depositId;
this.type = type;
this.totalResult = totalResult;
this.returnedResults = returnedResults;
this.pageIndex = pageIndex;
this.interchanges = interchanges;
this.declarationTdfc = declarationTdfc;
}
public String getDepositId() {
return depositId;
}
public void setDepositId(String depositId) {
this.depositId = depositId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getTotalResult() {
return totalResult;
}
public void setTotalResult(Integer totalResult) {
this.totalResult = totalResult;
}
public Integer getReturnedResults() {
return returnedResults;
}
public void setReturnedResults(Integer returnedResults) {
this.returnedResults = returnedResults;
}
public Integer getPageIndex() {
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Interchanges getInterchanges() {
return interchanges;
}
public void setInterchanges(Interchanges interchanges) {
this.interchanges = interchanges;
}
public DeclarationTdfc getDeclarationTdfc() {
return declarationTdfc;
}
public void setDeclarationTdfc(DeclarationTdfc declarationTdfc) {
this.declarationTdfc = declarationTdfc;
}
}
public class Interchanges {
#JacksonXmlProperty(localName = "interchange")
#JacksonXmlElementWrapper(useWrapping = false)
private List<Interchange> interchange;
public Interchanges() { super(); }
public Interchanges(List<Interchange> interchange) {
super();
this.interchange = interchange;
}
public List<Interchange> getInterchange() {
return interchange;
}
public void setInterchange(List<Interchange> interchange) {
this.interchange = interchange;
}
}
public class Interchange {
private String depositId;
private Integer interchangeId;
//#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = SelfmedConstants.Dates.ENGLISH_DATETIME_PATTERN)
private String depositDate;
private String depositSubject;
private String numADS;
//#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = SelfmedConstants.Dates.ENGLISH_DATETIME_PATTERN)
private String adsDate;
private String alias;
//#JacksonXmlProperty(isAttribute = true)
private String version;
#JsonSerialize(using = BooleanSerializer.class)
#JsonDeserialize(using = BooleanDeserializer.class)
#JacksonXmlProperty(localName = "isTest")
private Boolean isTest;
#JacksonXmlProperty(localName = "name")
#JacksonXmlElementWrapper(localName = "deposantAccount")
private List<String> name;
private String teleProcedure;
private StatesHistory statesHistory;
#JacksonXmlProperty(localName = "declarationId")
#JacksonXmlElementWrapper(localName = "declarationIds")
private List<String> declarationId;
public Interchange() {
}
public Interchange(String depositId, Integer interchangeId, String depositDate, String depositSubject, String numADS,
String adsDate, String alias, String version, Boolean isTest, List<String> name, String teleProcedure,
StatesHistory statesHistory, List<String> declarationId) {
this();
this.depositId = depositId;
this.interchangeId = interchangeId;
this.depositDate = depositDate;
this.depositSubject = depositSubject;
this.numADS = numADS;
this.adsDate = adsDate;
this.alias = alias;
this.version = version;
this.isTest = isTest;
this.name = name;
this.teleProcedure = teleProcedure;
this.statesHistory = statesHistory;
this.declarationId = declarationId;
}
public String getDepositId() {
return depositId;
}
public void setDepositId(String depositId) {
this.depositId = depositId;
}
public Integer getInterchangeId() {
return interchangeId;
}
public void setInterchangeId(Integer interchangeId) {
this.interchangeId = interchangeId;
}
public String getDepositDate() {
return depositDate;
}
public void setDepositDate(String depositDate) {
this.depositDate = depositDate;
}
public String getDepositSubject() {
return depositSubject;
}
public void setDepositSubject(String depositSubject) {
this.depositSubject = depositSubject;
}
public String getNumADS() {
return numADS;
}
public void setNumADS(String numADS) {
this.numADS = numADS;
}
public String getAdsDate() {
return adsDate;
}
public void setAdsDate(String adsDate) {
this.adsDate = adsDate;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Boolean getIsTest() {
return isTest;
}
public void setIsTest(Boolean isTest) {
this.isTest = isTest;
}
public void setIsTest(String isTest) {
this.isTest = Boolean.valueOf(isTest);
}
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
public String getTeleProcedure() {
return teleProcedure;
}
public void setTeleProcedure(String teleProcedure) {
this.teleProcedure = teleProcedure;
}
public StatesHistory getStatesHistory() {
return statesHistory;
}
public void setStatesHistory(StatesHistory statesHistory) {
this.statesHistory = statesHistory;
}
public List<String> getDeclarationId() {
return declarationId;
}
public void setDeclarationId(List<String> declarationId) {
this.declarationId = declarationId;
}
}
As you can see in the Interchange class, I try some stuff but nothing work.
I generate my class like that :
JacksonXmlModule xmlModule = new JacksonXmlModule();
xmlModule.setDefaultUseWrapper(false);
XmlMapper xmlMapper = new XmlMapper(xmlModule);
xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
xmlMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES);
System.out.println(responseAsString);
Envelope envelope = xmlMapper.readValue(responseAsString, new TypeReference<>() {
But when I try to parse my content, I got this exception :
Cannot construct instance of payload.response.Interchange (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('false')
at [Source: (StringReader); line: 20, column: 28] (through reference chain: payload.response.Envelope["Body"]->payload.response.Body["wsResponse"]->payload.response.WsResponse["response"]->payload.response.Response["successfullResponse"]->payload.response.SuccessfulResponse["interchanges"]->payload.response.Interchanges["interchange"]->java.util.ArrayList[1])
I try a lot of things but nothing work so I'm wondering if the problem may be not here...
If you have any solution or leads to explore, please let me know !
Thank.
According to JavaBean spec you have to name getter isTest().

Unable to retrieve document - Castexception ParameterizedType

I'm new to mongodb and struggle a bit. I want to store a class which contains a HashMap which contains other objects. When I store the object it works without any error and the document in the database looks good. But retrieving the document results in an error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
My (simplified) classes look like this:
#Entity(value = "abbyy_parameters", noClassnameStored = true)
public class AbbyyParameters extends AbstractModifiableMongoBean {
private String wordListEncoding = DEFAULT_ENCODING;
private String description;
private String name;
private PredefinedProfile predefinedProfile;
#Embedded
private CustomProfile customProfile;
private Parameters wordListActionParameters;
private Boolean treatBarcodeAsWord;
private Boolean documentProcessingEnabled;
private Boolean documentExportEnabled;
private Integer ocrPageLimit;
private Boolean highCommaFixEnabled;
private Double skewAngle;
private List<RegexBasedLanguage> regexBasedLanguages = new ArrayList<>(2);
public AbbyyParameters() {
this.createNewId();
this.setPredefinedProfile(new PredefinedProfile(PredefinedProfileType.DEFAULT));
this.setCustomProfile(new CustomProfile());
}
public String getWordListEncoding() {
return wordListEncoding;
}
public void setWordListEncoding(String encoding) {
if (!TangroUtils.isNullOrBlankString(encoding)) {
this.wordListEncoding = encoding;
}
}
public PredefinedProfile getPredefinedProfile() {
return predefinedProfile;
}
public void setPredefinedProfile(PredefinedProfile profile) {
if (profile == null) {
profile = new PredefinedProfile("Default");
}
this.predefinedProfile = profile;
}
public CustomProfile getCustomProfile() {
return customProfile;
}
public void setCustomProfile(CustomProfile profile) {
this.customProfile = profile;
}
public Optional<Boolean> isBarcodeTreatedAsWord() {
return Optional.ofNullable(treatBarcodeAsWord);
}
public void treatBarcodeAsWord(Boolean treatBarcodeAsWord) {
this.treatBarcodeAsWord = treatBarcodeAsWord;
}
public Optional<Boolean> isDocumentProcessingEnabled() {
return Optional.ofNullable(documentProcessingEnabled);
}
public void enableDocumentProcessing(Boolean enableDocumentProcessing) {
this.documentProcessingEnabled = enableDocumentProcessing;
}
public Optional<Boolean> isDocumentExportEnabled() {
return Optional.ofNullable(documentExportEnabled);
}
public void enableDocumentExport(Boolean exportDocument) {
this.documentExportEnabled = exportDocument;
}
public Optional<String> getDescription() {
return Optional.ofNullable(description);
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
public class CustomProfile {
private static final String DEFAULT_FILE_NAME = "custom";
#Transient
private String name;
#Embedded
private Map<String, ProfileProperties> properties = new HashMap<>(5);
public CustomProfile() {
}
public String getName() {
return name;
}
private void setName (String name) {
this.name = name;
}
public Map<String, ProfileProperties> getProperties() {
return properties;
}
private void setProperties(Map<String, ProfileProperties> properties) {
this.properties = properties;
}
}
#Embedded
public class ProfileProperties implements Iterable<ProfileProperty>, Serializable {
private static final long serialVersionUID = 1L;
#Embedded
private List<ProfileProperty> properties = new ArrayList<>(15);
public List<ProfileProperty> getProperties() {
return properties;
}
public void setProperties(List<ProfileProperty> properties) {
this.properties = properties;
}
public void add(ProfileProperty property) {
Optional<ProfileProperty> oldPropertyOpt = get(property.getName());
if (oldPropertyOpt.isPresent()) {
ProfileProperty oldProperty = oldPropertyOpt.get();
oldProperty.setValue(property.getValue());
} else {
properties.add(property);
}
}
public Optional<ProfileProperty> get(String propertyName) {
if (propertyName == null) {
return Optional.empty();
}
for(ProfileProperty property : properties) {
if (propertyName.equals(property.getName())) {
return Optional.of(property);
}
}
return Optional.empty();
}
#Override
public Iterator<ProfileProperty> iterator() {
return properties.iterator();
}
}
#Embedded
public class ProfileProperty implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String value;
public ProfileProperty(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I created morphia and told it how to map:
morphia = new Morphia();
morphia.map(AbbyyParameters.class,
CustomProfile.class,
ProfileProperties.class,
ProfileProperty.class);
After storing the class in the database the document look like this:
{
"_id" : ObjectId("5b2906a0cac45b8d42bbda91"),
"wordListEncoding" : "ISO-8859-15",
"description" : "",
"name" : "1",
"predefinedProfile" : {
"type" : "DEFAULT"
},
"customProfile" : {
"properties" : {
"PageAnalysisParams" : {
"properties" : [
{
"name" : "DetectBarcodes",
"value" : "true"
}
]
},
"RecognizerParams" : {
"properties" : [
{
"name" : "TextLanguage",
"value" : "English,German,Digits,French,Italian,Spanish,Croatian,Slovak,Bulgarian"
}
]
}
}
},
"treatBarcodeAsWord" : false,
"documentExportEnabled" : false,
"creationDate" : ISODate("2018-06-19T13:35:26.019Z"),
"changedDate" : ISODate("2018-06-19T13:35:28.441Z")
}
When I try to retrieve the document I get the following error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.mongodb.morphia.mapping.EmbeddedMapper.readMap(EmbeddedMapper.java:166)
I stepped into the code so I found that this code raises the exception:
new EphemeralMappedField((ParameterizedType) mf.getSubType(), mf, mapper);
mf.getSubType() returns ProfileProperties so I guess I have misconfigured something there?
What do I have to do that I can retrieve my document?

Using DataTables server-side with Spring Boot

I'm using jQuery DataTables in a Java Spring Boot project. When using DataTables's server-side processing, it sends AJAX request with request parameters like:
?columns[0][data]=0
&columns[0][name]=name
&columns[0][searchable]=true
&columns[0][orderable]=true
&columns[0][search][value]=Tom
&columns[0][search][regex]=false
&columns[1][data]=1
&columns[1][name]=address
&columns[1][searchable]=true
&columns[1][orderable]=true
&columns[1][search][value]=
&columns[1][search][regex]=false
to my server.
How can I convert these request parameters to a Java object for processing? The tutorial simply states that
In most modern server-side scripting environments this data will automatically be available to you as an array.
but I cannot find any way to do this in Java, particularly using Spring Boot's #RequestParameter.
Thank you for your help!
Create the following classes, ignore the package names
//DataTableRequest.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class DataTableRequest {
private String draw;
private List<Column> columns;
private List<Order> order;
private String start;
private String length;
private Search search;
private String empty;
#JsonProperty("draw")
public String getDraw() { return draw; }
#JsonProperty("draw")
public void setDraw(String value) { this.draw = value; }
#JsonProperty("columns")
public List<Column> getColumns() { return columns; }
#JsonProperty("columns")
public void setColumns(List<Column> value) { this.columns = value; }
#JsonProperty("order")
public List<Order> getOrder() { return order; }
#JsonProperty("order")
public void setOrder(List<Order> value) { this.order = value; }
#JsonProperty("start")
public String getStart() { return start; }
#JsonProperty("start")
public void setStart(String value) { this.start = value; }
#JsonProperty("length")
public String getLength() { return length; }
#JsonProperty("length")
public void setLength(String value) { this.length = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
#JsonProperty("_")
public String getEmpty() { return empty; }
#JsonProperty("_")
public void setEmpty(String value) { this.empty = value; }
}
// Column.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Column {
private String data;
private String name;
private String searchable;
private String orderable;
private Search search;
#JsonProperty("data")
public String getData() { return data; }
#JsonProperty("data")
public void setData(String value) { this.data = value; }
#JsonProperty("name")
public String getName() { return name; }
#JsonProperty("name")
public void setName(String value) { this.name = value; }
#JsonProperty("searchable")
public String getSearchable() { return searchable; }
#JsonProperty("searchable")
public void setSearchable(String value) { this.searchable = value; }
#JsonProperty("orderable")
public String getOrderable() { return orderable; }
#JsonProperty("orderable")
public void setOrderable(String value) { this.orderable = value; }
#JsonProperty("search")
public Search getSearch() { return search; }
#JsonProperty("search")
public void setSearch(Search value) { this.search = value; }
}
// Search.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Search {
private String value;
private String regex;
#JsonProperty("value")
public String getValue() { return value; }
#JsonProperty("value")
public void setValue(String value) { this.value = value; }
#JsonProperty("regex")
public String getRegex() { return regex; }
#JsonProperty("regex")
public void setRegex(String value) { this.regex = value; }
}
// Order.java
package com.employee.app.model;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Order {
private String column;
private String dir;
#JsonProperty("column")
public String getColumn() { return column; }
#JsonProperty("column")
public void setColumn(String value) { this.column = value; }
#JsonProperty("dir")
public String getDir() { return dir; }
#JsonProperty("dir")
public void setDir(String value) { this.dir = value; }
}
DataTables by default sends requests as FormData, to make it send that request as Json, do the following.
$(document).ready(function() {
$('#datatableId').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url: "your_processing_endpoint",
type:"POST",
contentType:"application/json",
data:function(d){
return JSON.stringify(d)
}
},
//include other options
} );
} );
And then in the controller action, assuming your are using Spring boot, do the following
#RequestMapping(value="your_processing_endpoint",method="RequestMethod.POST")
public ResponseEntity<?> processDataTableRequest(#RequestBody DataTableRequest
datatableRequest){
//you can add your logic here
}

How to deal with JSON response with same key "Value" its String and Array with Retrofit

In JSON Response there is key "Value" but its response have multiple forms like String and Array with same key "Value".
So how to make Retrofit model class to maintain String and Array with same key "Value".
{
"RespCode":"SUCCESS",
"RespText":"Transaction Details",
"Data":{
"Record":[
{
"group_title":"Seller Information",
"group_values":[
{
"key":"Listing Agent",
"value":[
{
"key":"Agent First Name",
"value":"Myks"
},
{
"key":"Agent Last Name",
"value":"Joe"
},
{
"key":"Company",
"value":"bdfjdlfdf"
},
{
"key":"Phone",
"value":"712.336.4967"
},
{
"key":"Email",
"value":"abc#gmail.com"
}
]
},
{
"key":"Cell Phone",
"value":"012.345.6789"
},
{
"key":"Email",
"value":"balt#gmail.com.com"
},
{
"key":"Preferred Contact Method",
"value":"Phone"
}
]
},
]
}
}
Just use an arraylist that contains multiple hashmaps maybe? Or... You have to define a pojo that has list of arrays with type map or something to that effect
Check this:
public class ModelBean {
private String RespCode;
private String RespText;
private DataBean Data;
public String getRespCode() {
return RespCode;
}
public void setRespCode(String RespCode) {
this.RespCode = RespCode;
}
public String getRespText() {
return RespText;
}
public void setRespText(String RespText) {
this.RespText = RespText;
}
public DataBean getData() {
return Data;
}
public void setData(DataBean Data) {
this.Data = Data;
}
public static class DataBean {
private List<RecordBean> Record;
public List<RecordBean> getRecord() {
return Record;
}
public void setRecord(List<RecordBean> Record) {
this.Record = Record;
}
public static class RecordBean {
private String group_title;
private List<GroupValuesBean> group_values;
public String getGroup_title() {
return group_title;
}
public void setGroup_title(String group_title) {
this.group_title = group_title;
}
public List<GroupValuesBean> getGroup_values() {
return group_values;
}
public void setGroup_values(List<GroupValuesBean> group_values) {
this.group_values = group_values;
}
public static class GroupValuesBean {
private String key;
private List<ValueBean> value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<ValueBean> getValue() {
return value;
}
public void setValue(List<ValueBean> value) {
this.value = value;
}
public static class ValueBean {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
}
}
}

Return a key-value list, key is attribute and value is attribute's value from other Class

I have a Class A with name and value attributes.
public class A {
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;
}
}
I have another Class B, such as
public class B {
private String attribute01;
private String attribute01;
private String attribute01;
public String getAttribute01() {
return attribute01;
}
public void setAttribute01(String name) {
this.attribute01 = name;
}
...
}
I would like to return a list with A type, having attribute01 key and where value is getAttribute01() from B, such as ({attribute01, getAttribute01()},{attribute02, getAttribute02()}).
How to implement it?.
Thanks in advance.
Actually I can use a very stupid way, such as
public List<A> keyvalueList(final B objB) {
List<A> list = new ArrayList<>();
A objA = new A();
objA.setName("attribute01");
objA.setValue(objB.getAttribute01());
list.add(objA);
objA = new A();
objA.setName("attribute02");
objA.setValue(objB.getAttribute02());
list.add(objA);
...
return list;
}
Part of them hard coding, obvious it is not a smart way, any proposal.
I wrote sample code for List.Please check my code that is ok to use or not.I added another extra class C.in C,it has two attribute String nameFromA and String attFromB.You should add this C object to list.Following is sample code.
public class A {
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;
}
}
public class B {
private String att1;
private String att2;
private String att3;
public String getAtt1() {
return att1;
}
public void setAtt1(String att1) {
this.att1 = att1;
}
public String getAtt2() {
return att2;
}
public void setAtt2(String att2) {
this.att2 = att2;
}
public String getAtt3() {
return att3;
}
public void setAtt3(String att3) {
this.att3 = att3;
}
}
public class C {
private String namefromA;
private String attfromB;
public String getNamefromA() {
return namefromA;
}
public void setNamefromA(String namefromA) {
this.namefromA = namefromA;
}
public String getAttfromB() {
return attfromB;
}
public void setAttfromB(String attfromB) {
this.attfromB = attfromB;
}
}
public class Test {
public static void main(String args[]){
C c = new C();
A a = new A();
B b = new B();
a.setName("A1");
b.setAtt1("100");
c.setNamefromA(a.getName());
c.setAttfromB(b.getAtt1());
List list = new ArrayList();
//use generic
list.add(c);
}
}
if you don't want to use class C,then you can use Test class like that
import java.util.ArrayList;
import java.util.List;
public class Test {
private String nameFromA;
private String valueFromB;
public Test(String nameFromA, String valueFromB) {
super();
this.nameFromA = nameFromA;
this.valueFromB = valueFromB;
}
public static void main(String args[]){
A a = new A();
B b = new B();
a.setName("A1");
b.setAtt1("100");
Test test = new Test(a.getName(),b.getAtt1());
List list = new ArrayList();
list.add(test);
}
}
This is my opinion only.Please check it is ok or not.

Categories