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
  • 1
    It seems that this is not proper JSON. Where do you get it from? Try with "[\"tdr1w6v\", \"tdr1w77\"]";. Commented Sep 10, 2015 at 17:51
  • Actually I mapped JSONArray to ArrayList<String> and dumped the ArrayList<String>.toString to db. Commented Sep 10, 2015 at 17:52
  • 2
    Convert JSONArray to string representing valid JSON structure if you want to retrieve it back using JSON parser. From which package JSONArray comes from? Commented Sep 10, 2015 at 17:55
  • {"path": [ "tdr1w6v", "tdr1w77" ]} Map it to ArrayList<String> path. Then use the model class to create a DAO and push data to data base. In the mapper for DAO implementation, I convert it to path.toString(). That is the format in which this method saves in db. Commented Sep 10, 2015 at 18:02
  • You can probably get the answer [here][1] [1]: stackoverflow.com/questions/7347856/… Commented Sep 10, 2015 at 18:02

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.