2
str = "[tdr1w6v, tdr1w77]";
ObjectMapper objectMapper = new ObjectMapper();
JavaType type = objectMapper.getTypeFactory().
                constructCollectionType(ArrayList.class, String.class);
ArrayList<String> list = null;
        try {
            list = objectMapper.readValue(str,
                    new TypeReference<ArrayList<String>>(){});
        } catch (IOException e) {
            e.printStackTrace();
        }

Here an exception is thrown :

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'tdr1w6v': was expecting 'null', 'true', 'false' or NaN

How can I convert str to ArrayList of string ?

11

2 Answers 2

3

@FedericoPeraltaSchaffner suggestion helped. Now what I do is, in my binder class use objectMapper.writeValueAsString to convert data to store in database. And in my Mapper class while reading from data base I can use the same way as in the question:

ObjectMapper objectMapper = new ObjectMapper();
ArrayList<String> list = null;
try {
        list =objectMapper.readValue(str, new TypeReference<ArrayList<String>>(){});
    } catch (IOException e) {
        e.printStackTrace();
    }

So now I don't have to create a separate DTO class, I can use the same model at service layer and DAO.

Sign up to request clarification or add additional context in comments.

Comments

1

The requirement can be easily met without using TypeReference

String str="[tdr1w6v, tdr1w77]";
List<String> al=Arrays.asList(str.replaceAll("[\\[\\]]","").split(","));
System.out.println(al);

1 Comment

Thanks. Your answer is same as suggested by @pmartin8.

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.