c# - Convert.ChangeType() signed type - changetype

How to convert unsigned integer using the method Convert.ChangeType() if I want to get the number is less than zero ?
Example
uint l = 0xFFF0;
short ret = (short)Convert.ChangeType(l, typeof(short)); // here error instead of -16

I am decided that the problem create own implementation class whith interface IConvertible.
Like this
/// Class that implements IConvertible
class ConvertData : IConvertible
{
public ConvertData(ulong Value)
{
_Field.UlongValue = Value;
}
public ConvertData():this(0)
{
}
public ulong Field
{
set { _Field.UlongValue = value; }
get { return _Field.UlongValue; }
}
ULongStruct _Field;
[StructLayout(LayoutKind.Explicit)]
struct ULongStruct
{
[FieldOffset(0)]
public ulong UlongValue;
[FieldOffset(0)]
public float FloatValue;
[FieldOffset(0)]
public double DoubleValue;
[FieldOffset(0)]
public uint UIntValue;
[FieldOffset(0)]
public int IntValue;
[FieldOffset(0)]
public ushort UShortValue;
[FieldOffset(0)]
public short ShortValue;
[FieldOffset(0)]
public byte ByteValue;
[FieldOffset(0)]
public sbyte SByteValue;
}
public TypeCode GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return _Field.ByteValue!=0;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return _Field.ByteValue;
}
char IConvertible.ToChar(IFormatProvider provider)
{
return (char)_Field.SByteValue;
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(_Field.UlongValue);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_Field.DoubleValue);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return _Field.DoubleValue;
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return _Field.ShortValue;
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return _Field.IntValue;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return (long)_Field.UlongValue;
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return _Field.SByteValue;
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return _Field.FloatValue;
}
string IConvertible.ToString(IFormatProvider provider)
{
return String.Format("({0})", _Field.UlongValue);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return Convert.ChangeType(_Field.UlongValue, conversionType);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return _Field.UShortValue;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return _Field.UIntValue;
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return _Field.UlongValue;
}
}
Call
ConvertData data = new ConvertData(l);
return (T)Convert.ChangeType(data, typeof(T));

Related

how to map json data which has dynamic fields like sku0,sku1 into a pojo class in java

below is my api response
{
"skuInventory": {
"sku0": {
"inventory": {
"PODate": {
"time": 1674363600000
},
"checkBackOrderQTY": false,
"allocatedQuantity": 127,
"endDate": {
"time": 1669216432575
},
"balanceQuantity": 4096,
"ltr60Days": true,
"modifiedDate": null,
"availableQuantity": 0,
"id": "VS-1261",
"dateFirstReceived": {
"time": 1136178000000
},
"totalOnOrder": 4858,
"remainDaysCurrDatePODate": 52,
"pendingBackorders": 0,
"presellFlag": false,
"storeInventory": true
},
"quantityLimitWebPageMsg": "",
"freeShippingPromoAmt": 25,
"notCartableBrandOOSMsg": "",
"cartableFlags": {
"bopusOnlyMessage": "Item is unavailable for shipping, please check local stores for pickup availability",
"ADP": "0",
"BOPUS": "1",
"consumeUpdateFlexShippingVerbiage": "true",
"DTCEstShippingMessage": "Temporarily Out of Stock",
"isProductFlexShippingFeeApplied": "false",
"cartableSku": "1",
"DTC": "0",
"DTCAvailablityMessage": "Temporarily Out of Stock",
"isProductFlexShippingFeeWaived": "false",
"DTCEstShipMsgSiteExp": "Temporarily Out of Stock",
"DTCAvMsgPDPRedesign": "Temporarily Out of Stock"
},
"quantityThreshold": 0
}
}
}
As we can see from above json structure there are multiple properties like sku0,sku1.sku2
I want to convert this json into POJO which i have created which is like below,
public class Root {
private SkuInventory skuInventory;
public SkuInventory getSkuInventory() {
return skuInventory;
}
public void setSkuInventory(SkuInventory skuInventory) {
this.skuInventory = skuInventory;
}
}
public class SkuInventory {
//#JsonAlias({ "sku0", "sku1", "sku2" })
private List<Sku0> sku0;
public List<Sku0> getSku0() {
return sku0;
}
public void setSku0(List<Sku0> sku0) {
this.sku0 = sku0;
}
}
public class Sku {
private Inventory inventory;
private String quantityLimitWebPageMsg;
private int freeShippingPromoAmt;
private String notCartableBrandOOSMsg;
private CartableFlags cartableFlags;
private int quantityThreshold;
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public String getQuantityLimitWebPageMsg() {
return quantityLimitWebPageMsg;
}
public void setQuantityLimitWebPageMsg(String quantityLimitWebPageMsg) {
this.quantityLimitWebPageMsg = quantityLimitWebPageMsg;
}
public int getFreeShippingPromoAmt() {
return freeShippingPromoAmt;
}
public void setFreeShippingPromoAmt(int freeShippingPromoAmt) {
this.freeShippingPromoAmt = freeShippingPromoAmt;
}
public String getNotCartableBrandOOSMsg() {
return notCartableBrandOOSMsg;
}
public void setNotCartableBrandOOSMsg(String notCartableBrandOOSMsg) {
this.notCartableBrandOOSMsg = notCartableBrandOOSMsg;
}
public CartableFlags getCartableFlags() {
return cartableFlags;
}
public void setCartableFlags(CartableFlags cartableFlags) {
this.cartableFlags = cartableFlags;
}
public int getQuantityThreshold() {
return quantityThreshold;
}
public void setQuantityThreshold(int quantityThreshold) {
this.quantityThreshold = quantityThreshold;
}
}
public class Inventory {
#JsonProperty("PODate")
private Time pODate;
private boolean checkBackOrderQTY;
private int allocatedQuantity;
private Time endDate;
private int balanceQuantity;
private boolean ltr60Days;
private Object modifiedDate;
private int availableQuantity;
private String id;
private Time dateFirstReceived;
private int totalOnOrder;
private int remainDaysCurrDatePODate;
private int pendingBackorders;
private boolean presellFlag;
private boolean storeInventory;
public Time getpODate() {
return pODate;
}
public void setpODate(Time pODate) {
this.pODate = pODate;
}
public boolean isCheckBackOrderQTY() {
return checkBackOrderQTY;
}
public void setCheckBackOrderQTY(boolean checkBackOrderQTY) {
this.checkBackOrderQTY = checkBackOrderQTY;
}
public int getAllocatedQuantity() {
return allocatedQuantity;
}
public void setAllocatedQuantity(int allocatedQuantity) {
this.allocatedQuantity = allocatedQuantity;
}
public Time getEndDate() {
return endDate;
}
public void setEndDate(Time endDate) {
this.endDate = endDate;
}
public int getBalanceQuantity() {
return balanceQuantity;
}
public void setBalanceQuantity(int balanceQuantity) {
this.balanceQuantity = balanceQuantity;
}
public boolean isLtr60Days() {
return ltr60Days;
}
public void setLtr60Days(boolean ltr60Days) {
this.ltr60Days = ltr60Days;
}
public Object getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
public int getAvailableQuantity() {
return availableQuantity;
}
public void setAvailableQuantity(int availableQuantity) {
this.availableQuantity = availableQuantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Time getDateFirstReceived() {
return dateFirstReceived;
}
public void setDateFirstReceived(Time dateFirstReceived) {
this.dateFirstReceived = dateFirstReceived;
}
public int getTotalOnOrder() {
return totalOnOrder;
}
public void setTotalOnOrder(int totalOnOrder) {
this.totalOnOrder = totalOnOrder;
}
public int getRemainDaysCurrDatePODate() {
return remainDaysCurrDatePODate;
}
public void setRemainDaysCurrDatePODate(int remainDaysCurrDatePODate) {
this.remainDaysCurrDatePODate = remainDaysCurrDatePODate;
}
public int getPendingBackorders() {
return pendingBackorders;
}
public void setPendingBackorders(int pendingBackorders) {
this.pendingBackorders = pendingBackorders;
}
public boolean isPresellFlag() {
return presellFlag;
}
public void setPresellFlag(boolean presellFlag) {
this.presellFlag = presellFlag;
}
public boolean isStoreInventory() {
return storeInventory;
}
public void setStoreInventory(boolean storeInventory) {
this.storeInventory = storeInventory;
}
}
Below is the codee to map json into a POJO
ResponseEntity<?> inventoryData = (ResponseEntity<?>) inventoryAPIResponse.getData();
Map<?, ?> inventoryBody = (Map<?, ?>) inventoryData.getBody();
Root atgInventory = getObjectMapper().convertValue(inventoryBody, Root.class);
Sku availableQuantity = (Sku) atgInventory.getSkuInventory().getSku();
If we execute above code we get errors like this
java.lang.IllegalArgumentException: Cannot deserialize value of type `java.util.ArrayList<Sku>` from Object value (token `JsonToken.START_OBJECT`)
at [Source: UNKNOWN; byte offset: #UNKNOWN] (through reference chain: Root["skuInventory"]->SkuInventory["sku0"])
How can wee resolve this issue of mapping a json to a pojo which has a property which is dynamic like sku0,sku1,sku2 etc??
I would introduce a Map as follows:
public class Root {
private Map<String, Sku> skuInventory;
}
This Map will then replace your SkuInventory object and has keys like Sku0, Sku1 etc.

Can Jackson be configured to deserialize the JSON Key (Not value)?

I am trying to trim the JSON key in order to avoid spaces in the JSON requests.
JSON Object would look like with white space, (check for "eq")
{
"page": 0,
"size": 25,
"and":{
"eq ": [
{
"field":"id",
"value": "60536"
}
]
}
}
I find lot of solution ranging from SimpleModule to JsonDeserializer but all generally work on the value part. How can I trim the key itself which then correctly converts into my Java POJO?
public class SearchInDTO implements InDTO {
private Integer pageNo;
private Integer pageSize;
private ANDFilter andFilter;
#JsonProperty("page")
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
#JsonProperty("size")
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
#JsonProperty("and")
public ANDFilter getAndFilter() {
return andFilter;
}
public void setAndFilter(ANDFilter andFilter) {
this.andFilter = andFilter;
}
public static class EQFilter extends FieldValue
{
#JsonProperty("field")
public String getFieldName() {
return super.getFieldName();
}
#JsonProperty("value")
public String getValue() {
return super.getValue();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("EQFilter{");
sb.append(super.toString());
sb.append('}');
return sb.toString();
}
}
public static class FieldValue
{
private String fieldName;
private String value;
#JsonProperty("field")
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("value")
public String getValue() {
if(value == null) return value;
return value.toLowerCase();
}
public void setValue(String value) {
this.value = value;
}
}
public static class ANDFilter {
private List<EQFilter> eqFilters = new ArrayList<>();
#JsonProperty("eq")
public List<EQFilter> getEqFilters() {
return eqFilters;
}
public void setEqFilters(List<EQFilter> eqFilters) {
this.eqFilters = eqFilters;
}
}
}
Solution with custom JsonParser implementation:
public class MyJsonParser extends JsonParserDelegate {
public MyJsonParser(JsonParser parser) {
super(parser);
}
#Override
public String getCurrentName() throws IOException {
return super.getCurrentName().trim();
}
}
public class MyJsonParserFactory extends MappingJsonFactory {
#Override
protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(in, ctxt));
}
#Override
protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(r, ctxt));
}
#Override
protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, boolean recyclable) throws IOException {
return new MyJsonParser(super._createParser(data, offset, len, ctxt, recyclable));
}
#Override
protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(data, offset, len, ctxt));
}
#Override
protected JsonParser _createParser(DataInput input, IOContext ctxt) throws IOException {
return new MyJsonParser(super._createParser(input, ctxt));
}
}
#Component
public class MyJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
#Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.factory(new MyJsonParserFactory());
}
}

415 error while trying to post json array to spring rest controller

My json request is as follows
{
"division":"XX",
"category":"XX",
"operation":"XXX",
"transactionId":"XX",
"trackNumber":"XXx",
"attentionReason":"",
"carNeedAttention":"",
"chargableDamage":"X",
"missingItems":"",
"offences":"N",
"outInAgentNumber":"XX",
"cList":{
{
"id":"230",
"elementCode":"XXX",
"value":"XXX",
"comment":"XX",
"label":"",
"uiComponent":"",
"featureType":""
}
},
"outInCprNumber":"XX",
"outInDate":"",
"outInDuration":"",
"outInFuel":"75",
"outInKm":"9999",
"outInRem1":"",
"outInRem2":"",
"outInRem3":"",
"userName":"XX",
"vehicleRetBy":""
}
I have a spring rest controller class
#Controller
#RequestMapping("/services")
public class CheckListController {
#RequestMapping(value = "/checkList", method = RequestMethod.POST, consumes="application/json",produces="application/json")
public ModelMap updateCheckList(#RequestBody CheckList checkList){
ModelMap modelMap = new ModelMap();
return modelMap;
}
}
CheckList class is as follows
import java.util.List;
public class CheckList {
String division;
String category;
String operation;
String transactionId;
String trackNumber;
String attentionReason;
String carNeedAttention;
String chargableDamage;
String missingItems;
String offences;
String outInAgentNumber;
List<MetaData> cList;
String outInCprNumber;
String outInDate;
String outInDuration;
String outInFuel;
String outInKm;
String outInRem1;
String outInRem2;
String outInRem3;
String userName;
String vehicleRetBy;
String updateMasterImage;
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getTrackNumber() {
return trackNumber;
}
public void setTrackNumber(String trackNumber) {
this.trackNumber = trackNumber;
}
public String getAttentionReason() {
return attentionReason;
}
public void setAttentionReason(String attentionReason) {
this.attentionReason = attentionReason;
}
public String getCarNeedAttention() {
return carNeedAttention;
}
public void setCarNeedAttention(String carNeedAttention) {
this.carNeedAttention = carNeedAttention;
}
public String getChargableDamage() {
return chargableDamage;
}
public void setChargableDamage(String chargableDamage) {
this.chargableDamage = chargableDamage;
}
public String getMissingItems() {
return missingItems;
}
public void setMissingItems(String missingItems) {
this.missingItems = missingItems;
}
public String getOffences() {
return offences;
}
public void setOffences(String offences) {
this.offences = offences;
}
public List<MetaData> getcList() {
return cList;
}
public void setcList(List<MetaData> cList) {
this.cList = cList;
}
// public AccessoryList getAccessoryList() {
// return accessoryList;
// }
//
// public void setAccessoryList(AccessoryList accessoryList) {
// this.accessoryList = accessoryList;
// }
public String getOutInCprNumber() {
return outInCprNumber;
}
public void setOutInCprNumber(String outInCprNumber) {
this.outInCprNumber = outInCprNumber;
}
public String getOutInDate() {
return outInDate;
}
public void setOutInDate(String outInDate) {
this.outInDate = outInDate;
}
public String getOutInRem1() {
return outInRem1;
}
public void setOutInRem1(String outInRem1) {
this.outInRem1 = outInRem1;
}
public String getOutInRem2() {
return outInRem2;
}
public void setOutInRem2(String outInRem2) {
this.outInRem2 = outInRem2;
}
public String getOutInRem3() {
return outInRem3;
}
public void setOutInRem3(String outInRem3) {
this.outInRem3 = outInRem3;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getVehicleRetBy() {
return vehicleRetBy;
}
public void setVehicleRetBy(String vehicleRetBy) {
this.vehicleRetBy = vehicleRetBy;
}
public String getUpdateMasterImage() {
return updateMasterImage;
}
public void setUpdateMasterImage(String updateMasterImage) {
this.updateMasterImage = updateMasterImage;
}
public String getOutInAgentNumber() {
return outInAgentNumber;
}
public void setOutInAgentNumber(String outInAgentNumber) {
this.outInAgentNumber = outInAgentNumber;
}
public String getOutInDuration() {
return outInDuration;
}
public void setOutInDuration(String outInDuration) {
this.outInDuration = outInDuration;
}
public String getOutInFuel() {
return outInFuel;
}
public void setOutInFuel(String outInFuel) {
this.outInFuel = outInFuel;
}
public String getOutInKm() {
return outInKm;
}
public void setOutInKm(String outInKm) {
this.outInKm = outInKm;
}
}
MetaData is as folows
public class MetaData{
Integer id;
String label;
String uiComponent;
String featureType;
String value;
String comment;
String elementCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(int id)
{
this.id = id;
}
public String getLabel()
{
return label;
}
public void setLabel(String label)
{
this.label = label;
}
public String getUiComponent()
{
return uiComponent;
}
public void setUiComponent(String uiComponent)
{
this.uiComponent = uiComponent;
}
public String getFeatureType()
{
return featureType;
}
public void setFeatureType(String featureType)
{
this.featureType = featureType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getElementCode() {
return elementCode;
}
public void setElementCode(String elementCode) {
this.elementCode = elementCode;
}
}
But when i submitting the json request it is giving 415 unsuporrted media type error.
What is wrong with this code. Do anybody havve the answer. Thanks in advance.
Nothing with the code. You just need to make sure that Your POST request has the HTTP Content-Type header set to "application/json".
If you use curl to POST the data you can use the following parameter to set the header value:
curl -H "Content-Type:application/json"
Add an Accept header too:
curl -H "Content-Type:application/json" -H "Accept:application/json"

javax.ejb.EJBException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

GSON Throwing Syntax exception While parsing the JSON into a Java Objects. Here I have attached my JSON and the Classes by which JSON has been parsed and the code where I am parsing the JSON values. Please help me to fix this error.
The following is my JSON Response Which is to be parsed.
JSON
[
{ "counter":1,
"data":{
"b":[
{"d":11.080666011022274,"e":-9.84375},
{"d":21.36033117555945,"e":-13.18359375},
{"d":25.55169302685644,"e":-5.09765625},
{"d":20.209969075006228,"e":24.9609375},
{"d":6.740259027196141,"e":27.7734375},
{"d":19.38301389529031,"e":10.01953125}
],
"gm_accessors_":{"length":null},
"length":6,
"gm_bindings_":{"length":{}}
}
},
{ "counter":2,
"data":{
"b":[
{"d":43.76263306667474,"e":60.1171875},
{"d":56.310038487065135,"e":47.8125},
{"d":60.881999484084055,"e":78.22265625},
{"d":55.81939178481952,"e":96.6796875},
{"d":44.76961886697326,"e":99.84375},
{"d":55.72051189919337,"e":82.08984375},
{"d":40.50489156437503,"e":81.5625},
{"d":52.74250152629922,"e":72.0703125}
],
"gm_accessors_":{"length":null},
"length":8,
"gm_bindings_":{"length":{}}
}
}
]
The Above Json has been parsed by the following JAVA classes. In the following Class structure I am making Mistake. Please guide me where I am doing the mistake.
**Parent Class -- SHAPE**
public class Shape {
#SerializedName("counter")
private Integer mCounter;
#SerializedName("data")
private Data mData;
public Data getmData() {
return mData;
}
public void setmData(Data mData) {
this.mData = mData;
}
public Integer getCounter() {
return mCounter;
}
public void setCounter(Integer counter) {
this.mCounter = counter;
}
}
**CHILD CLASS -- DATA**
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
private b mCoordinates;
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public b getmCoordinates() {
return mCoordinates;
}
public void setmCoordinates(b mCoordinates) {
this.mCoordinates = mCoordinates;
}
}
**GRAND CHILD CLASS -- b**
public class b {
#SerializedName("d")
private ArrayList<Float> lattitude;
#SerializedName("e")
private ArrayList<Float> longtitude;
public ArrayList<Float> getLattitude() {
return lattitude;
}
public void setLattitude(ArrayList<Float> lattitude) {
this.lattitude = lattitude;
}
public ArrayList<Float> getLongtitude() {
return longtitude;
}
public void setLongtitude(ArrayList<Float> longtitude) {
this.longtitude = longtitude;
}
}
JSON PARSING -- CHANGING JSON AS A JAVA OBJECTS
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(jsonContent).getAsJsonArray();
System.out.println("Array :_: " + jArray);
for(JsonElement jsonElement : jArray) {
System.out.println("JSON_ELEMENT :_: " + jsonElement);
Shape shape = gson.fromJson(jsonElement, Shape.class);
System.out.println("Counter :_: " + shape.getCounter());
}
Please chnage your data class to :
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
// this is where the error was thrown,
// it was expecting an array but only received a single object.
private List<b> mCoordinates;
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public List<b> getmCoordinates() {
return mCoordinates;
}
public void setmCoordinates(List<b> mCoordinates) {
this.mCoordinates = mCoordinates;
}
}
And also change the b class to:
public class b {
#SerializedName("d")
private double d;
#SerializedName("e")
private double e;
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public double getE() {
return e;
}
public void setE(double e) {
this.e = e;
}
}
use:
Gson gson = new Gson();
Shape shape = gson.fromJson(reader/string here, Shape.class);
and your shape class will be filled.
public class Shape {
#SerializedName("counter")
private Integer mCounter;
#SerializedName("data")
private Data mData;
// geter/setter here
}
public class Data {
#SerializedName("length")
private Integer length;
#SerializedName("b")
private List<Coordinate> coordinates;
#SerializedName("gm_accessors_")
private Accessors gmAccessors;
//getter setter here
}
public class Coordinate {
private float d;
private float e;
}
public class Accessors {
private Integer length;
}
Finally Parse it as
Shape[] shapes = gson.fromJson(jArray, Shape[].class);
If you will parse like this you will get same error : Expected BEGIN_OBJECT but was BEGIN_ARRAY
Shape shape = gson.fromJson(jArray, Shape.class);

dropwizard: incorrect json resulting from group of items

I am using Dropwizard to deliver a RESTful service. The JSON I EXPECT looks like this:
{"featuredMerchants":
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}}
But the JSON I am GETTING is this:
{"featuredMerchant":[
{"browseId":"v1_0_0_1112",
"merchantId":3902,
"priority":1,
"sourceId":"15"},
...,
{"browseId":"v1_0_0_1112",
"merchantId":456,
"priority":4,
"sourceId":"15"}]}
I have two classes. I have an ApiFeaturedMerchantGroup class that contains a list of ApiFeaturedMerchants.
#JsonRootName("featuredMerchants")
public class ApiFeaturedMerchantGroup {
private List<ApiFeaturedMerchant> apiFeaturedMerchants;
public ApiFeaturedMerchantGroup() {
}
#JsonProperty("featuredMerchant")
public List<ApiFeaturedMerchant> getApiFeaturedMerchants() { return apiFeaturedMerchants; }
public void setApiFeaturedMerchants(List<ApiFeaturedMerchant> apiFeaturedMerchants) { this.apiFeaturedMerchants = apiFeaturedMerchants; }
}
#JsonRootName("featuredMerchant")
public class ApiFeaturedMerchant {
private String browseId;
private int merchantId;
private Integer priority;
private String sourceId;
public ApiFeaturedMerchant() {
}
public String getBrowseId() { return browseId; }
public void setBrowseId(String browseId) { this.browseId = browseId; }
public int getMerchantId() { return merchantId; }
public void setMerchantId(int merchantId) { this.merchantId = merchantId; }
public Integer getPriority() { return priority; }
public void setPriority(Integer priority) { this.priority = priority; }
public String getSourceId() { return sourceId; }
public void setSourceId(String sourceId) { this.sourceId = sourceId; }
}
How do I get the extra level into my JSON, the "featuredMerchants" group that contains the individual "featuredMerchant" items? Do I have the wrong annotations, or am I missing one/some?
It's a setting on ObjectMapperFactory:
ObjectMapperFactory objectMapperFactory = new ObjectMapperFactory();
objectMapperFactory.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper = objectMapperFactory.build();