Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON array to Java Class Object List

Tags:

java

json

android

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!

like image 541
Vlad Marinescu Avatar asked Sep 26 '22 13:09

Vlad Marinescu


2 Answers

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();
       } 
like image 197
Fabio Venturi Pastor Avatar answered Sep 28 '22 05:09

Fabio Venturi Pastor


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();
like image 38
Ronak Joshi Avatar answered Sep 28 '22 05:09

Ronak Joshi