5

I have a JSON string that comes from a WFC service. When I try to convert JSON array into List object, I've got the following error :

".JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader@41f27f18; line: 1, column: 1]"

The Java class (Card Class):

public class Card {
    public String ID;
    public String CompanyID;
    public String CompanyName;
    public String FiscalCode;
    public String Limit;
    public String StateID;
    public String CardState;
    public String Deleted;
    public String Sold;
    public String StartDate;
    public String InvoiceStartDate;
    public String Quantity;
    public String Value;
    public String CardTypeID;
    public String CardType;
    public String SoldChanged;
    public String DriverName;
    public String VehiclePlateNumber;
    public String VehicleID;
    public String Discount;
    public String ContractID;
    public String DiscountPerMonth;
    public String ProductID;
    public String ProductStateID;
    public String Mail;
    public String WithoutLimit;
    public String ContractSold;
    public String ContractLimit;
    public String NumberOfTransactions;
    public String DriverNameOnly;
    public String DriverSurnameOnly;
}

The Java code to deserialize :

strResponse = responseHandler.handleResponse(response);
if (strResponse.contains("Credit") || strResponse.contains("Debit")) {
    ObjectMapper mapper = new ObjectMapper();
    strResponse= strResponse.replace("\"GetCardsResult\":", "");
    userCards = mapper.readValue(strResponse, mapper.getTypeFactory().constructCollectionType(List.class, Card.class));
}

The JSON string:

{     "GetCardsResult":"[{\"ID\":3,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"1423127205\",\"Limit\":0.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":0.000,\"StartDate\":\"\/Date(1412974800000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"\",\"VehiclePlateNumber\":\"B 222 ART\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null},{\"ID\":2881,\"CompanyID\":1155,\"CompanyName\":\"test\",\"FiscalCode\":null,\"Code\":\"test0000\",\"Limit\":125.000,\"StateID\":1,\"CardState\":\"Activ\",\"Deleted\":false,\"Sold\":132.330,\"StartDate\":\"\/Date(1436130000000+0300)\/\",\"InvoiceStartDate\":\"\/Date(-62135596800000+0200)\/\",\"Quantity\":null,\"Value\":0.0,\"CardTypeID\":1,\"CardType\":\"Credit\",\"SoldChanged\":false,\"DriverName\":\"aaa aaa\",\"VehiclePlateNumber\":\"aaa\",\"VehicleID\":null,\"Discount\":null,\"ContractID\":15,\"DiscountPerMonth\":null,\"ProductID\":null,\"ProductStateID\":null,\"Mail\":\"\",\"WithoutLimit\":true,\"ContractSold\":null,\"ContractLimit\":null,\"NumberOfTransactions\":null,\"DriverNameOnly\":null,\"DriverSurnameOnly\":null}]" }

Thanks in advance!

12
  • How you converting json string into Object class ? Commented Jan 27, 2016 at 10:15
  • I thought ObjectMapper does that :) That's why all my class variables are strings Commented Jan 27, 2016 at 10:35
  • I guess he is using com.fasterxml.jackson.databind.ObjectMapper. Commented Jan 27, 2016 at 10:52
  • org.json.JSONObject; Commented Jan 27, 2016 at 10:53
  • strResponse= strResponse.replace("\"GetCardsResult\":", ""); will destroy your JSON. You're only removing the key and the colon, not the leading and trailing curly braces. Additionally: your code is highly inefficient (has to work through the string up to four times) and likely to break (e.g. the webservice returns formatted JSON with a space in front of the colon) Commented Jan 27, 2016 at 10:53

3 Answers 3

3

Try this:

    try {            
         JSONObject jsonObject = null;
         yourJSONString.replace("\\", "");
         jsonObject = new JSONObject(yourJSONString);
         String newJSONString = jsonObject.get("GetCardsResult").toString();
         JSONArray jsonMainArr = new JSONArray(newJSONString);
         //now just loop the json Array
         for (int i = 0; i < jsonMainArr.length(); ++i) {                     
         JSONObject rec = jsonMainArr.getJSONObject(i);                     
         card.set_id(rec.get("ID").toString());                     
         //....      
       }                                                       
       } catch (JSONException e) {
         e.printStackTrace();
       } 
Sign up to request clarification or add additional context in comments.

2 Comments

yourJSONString.replace("\\", ""); Is it required??
2

Try to use GSON its very efficient and easy to implement, As example below will be your POJO class.

public class Post {

    @SerializedName("id")
    public long ID;
    public String title;
    public String author;
    public String url;
    @SerializedName("date")
    public Date dateCreated;
    public String body;

    public List tags;

    public Post() {

    }
}

//Tag.java
public class Tag {

    public String name;
    public String url;

    public Tag() {

    }
}

And this will how you parse your JSON string to Object Class,

Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
posts = Arrays.asList(gson.fromJson(reader, Post[].class));
content.close();

Comments

0
  1. What do you pass to the mapper - string before or after compiling the regular expression?

  2. Did you try any external lib like Gson? Everything you need is just new Gson().fromJson(strResponse, new TypeToken<List<Card>>() {}.getType(););

4 Comments

userCards= gs.fromJson(strResponse, new TypeToken<List<Card>>() {}.getType()); java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
what about new Gson().fromJson(strResponse, Card.class);
you thought that there's an object , not an array?
Can't convert Array to Card object. For sure, there's an array in JSON response. There are more than 1 card info, so , I need array , only if somehow I convert object by object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.